在哪里声明类常量? [英] Where to declare class constants?
问题描述
我正在使用类成员来保存常量。例如:
I'm using class members to hold constants. E.g.:
function Foo() {
}
Foo.CONSTANT1 = 1;
Foo.CONSTANT2 = 2;
这样可以正常工作,除了它似乎有点无组织,所有代码都是特定的 Foo
在全球范围内铺设。所以我考虑将常量声明移到 Foo()
声明中,但不会每次都执行该代码 Foo
构建了吗?
This works fine, except that it seems a bit unorganized, with all the code that is specific to Foo
laying around in global scope. So I thought about moving the constant declaration to inside the Foo()
declaration, but then wouldn't that code execute everytime Foo
is constructed?
我来自Java,其中所有东西都包含在一个类体中,所以我认为JavaScript可能有类似的东西或一些工作模仿它。
I'm coming from Java where everything is enclosed in a class body, so I'm thinking JavaScript might have something similar to that or some work around that mimics it.
推荐答案
你在代码中所做的只是添加一个名为的属性CONSTANT
,将值 1
添加到名为Foo的Function对象,然后立即使用值 2 $ c $覆盖它c>。
All you're doing in your code is adding a property named CONSTANT
with the value 1
to the Function object named Foo, then overwriting it immediately with the value 2
.
我对其他语言并不太熟悉,但我不相信javascript能够做你想做的事情。
I'm not too familiar with other languages, but I don't believe javascript is able to do what you seem to be attempting.
您要添加到 Foo
的所有属性都不会执行。它们只是存储在那个命名空间中。
None of the properties you're adding to Foo
will ever execute. They're just stored in that namespace.
也许你想把一些属性原型化到 Foo
?
Maybe you wanted to prototype some property onto Foo
?
function Foo() {
}
Foo.prototype.CONSTANT1 = 1;
Foo.prototype.CONSTANT2 = 2;
虽然不是你想要的。
这篇关于在哪里声明类常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!