在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"仍然为真。
其他回答
在JavaScript中引入常量充其量是一种hack。
在JavaScript中创建持久且全局可访问的值的一个好方法是声明一个具有“只读”属性的对象文字,如下所示:
my={get constant1(){return "constant 1"},
get constant2(){return "constant 2"},
get constant3(){return "constant 3"},
get constantN(){return "constant N"}
}
你可以将你所有的常量组合在一个单独的“my”附属对象中,在那里你可以查找你存储的值或其他任何你决定放在那里的东西。现在让我们来测试一下它是否有效:
my.constant1; >> "constant 1"
my.constant1 = "new constant 1";
my.constant1; >> "constant 1"
正如我们所看到的,“我的”。Constant1”属性保留了其原始价值。你已经为自己设置了一些不错的“绿色”临时常数……
当然,这只能防止您意外地修改、修改、无效或清空您的属性常量值,就像在给定的例子中那样。
否则我仍然认为常数是傻瓜用的。 我仍然认为,用你巨大的自由换取一个小小的欺骗性的安全是最糟糕的交易。
有一段时间,我在传递给with()语句的对象字面量中指定了“常量”(实际上仍然不是常量)。我觉得这很聪明。这里有一个例子:
with ({
MY_CONST : 'some really important value'
}) {
alert(MY_CONST);
}
在过去,我还创建了一个CONST名称空间,将所有常量放在其中。还有开销。天哪。
现在,我写var MY_CONST = 'whatever';吻。
关键字“const”早前就被提出了,现在它已经被正式包含在ES6中。通过使用const关键字,可以传递一个作为不可变字符串的值/字符串。
除了上面提到的,Rhino.js还实现了const。
伯克的答案的改进版本,让你做CONFIG。MY_CONST代替CONFIG.get('MY_CONST')。
它需要IE9+或真正的网络浏览器。
var CONFIG = (function() {
var constants = {
'MY_CONST': 1,
'ANOTHER_CONST': 2
};
var result = {};
for (var n in constants)
if (constants.hasOwnProperty(n))
Object.defineProperty(result, n, { value: constants[n] });
return result;
}());
*属性是只读的,只有初始值是不可变的。