在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"仍然为真。
其他回答
"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。
伯克的答案的改进版本,让你做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;
}());
*属性是只读的,只有初始值是不可变的。
有一段时间,我在传递给with()语句的对象字面量中指定了“常量”(实际上仍然不是常量)。我觉得这很聪明。这里有一个例子:
with ({
MY_CONST : 'some really important value'
}) {
alert(MY_CONST);
}
在过去,我还创建了一个CONST名称空间,将所有常量放在其中。还有开销。天哪。
现在,我写var MY_CONST = 'whatever';吻。
从ES2015开始,JavaScript有了const的概念:
const MY_CONSTANT = "some-value";
这将工作在几乎所有的浏览器除了ie8, 9和10。有些可能还需要启用严格模式。
如果你需要支持旧的浏览器或使用遗留代码,你可以使用var和像ALL_CAPS这样的约定来表明某些值不应该被修改:
var MY_CONSTANT = "some-value";
IE确实支持常量,比如:
<script language="VBScript">
Const IE_CONST = True
</script>
<script type="text/javascript">
if (typeof TEST_CONST == 'undefined') {
const IE_CONST = false;
}
alert(IE_CONST);
</script>