在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
另一种选择是:
var constants = {
MY_CONSTANT : "myconstant",
SOMETHING_ELSE : 123
}
, constantMap = new function ConstantMap() {};
for(var c in constants) {
!function(cKey) {
Object.defineProperty(constantMap, cKey, {
enumerable : true,
get : function(name) { return constants[cKey]; }
})
}(c);
}
然后简单地:var foo = constantMap。MY_CONSTANT
如果你使用constantMap。MY_CONSTANT = "bar"它不会有任何影响,因为我们试图使用赋值操作符和getter,因此使用constantMap。MY_CONSTANT === "myconstant"仍然为真。
其他回答
有一段时间,我在传递给with()语句的对象字面量中指定了“常量”(实际上仍然不是常量)。我觉得这很聪明。这里有一个例子:
with ({
MY_CONST : 'some really important value'
}) {
alert(MY_CONST);
}
在过去,我还创建了一个CONST名称空间,将所有常量放在其中。还有开销。天哪。
现在,我写var MY_CONST = 'whatever';吻。
我在Greasemonkey脚本中使用const而不是var,但这是因为它们只会在Firefox上运行… 名称约定也确实是可行的方法(我两者都做!)
"use strict";
var constants = Object.freeze({
"π": 3.141592653589793 ,
"e": 2.718281828459045 ,
"i": Math.sqrt(-1)
});
constants.π; // -> 3.141592653589793
constants.π = 3; // -> TypeError: Cannot assign to read only property 'π' …
constants.π; // -> 3.141592653589793
delete constants.π; // -> TypeError: Unable to delete property.
constants.π; // -> 3.141592653589793
看到Object.freeze。如果想让常量引用只读,也可以使用const。
除了上面提到的,Rhino.js还实现了const。
如果值得一提的话,你可以使用$ provider .constant()在angular中定义常量
angularApp.constant('YOUR_CONSTANT', 'value');