在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
有一段时间,我在传递给with()语句的对象字面量中指定了“常量”(实际上仍然不是常量)。我觉得这很聪明。这里有一个例子:
with ({
MY_CONST : 'some really important value'
}) {
alert(MY_CONST);
}
在过去,我还创建了一个CONST名称空间,将所有常量放在其中。还有开销。天哪。
现在,我写var MY_CONST = 'whatever';吻。
其他回答
您可以轻松地为脚本配备一种用于常量的机制,这些常量可以设置但不能更改。试图更改它们将产生错误。
/* author Keith Evetts 2009 License: LGPL
anonymous function sets up:
global function SETCONST (String name, mixed value)
global function CONST (String name)
constants once set may not be altered - console error is generated
they are retrieved as CONST(name)
the object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided
*/
(function(){
var constants = {};
self.SETCONST = function(name,value) {
if (typeof name !== 'string') { throw new Error('constant name is not a string'); }
if (!value) { throw new Error(' no value supplied for constant ' + name); }
else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); }
else {
constants[name] = value;
return true;
}
};
self.CONST = function(name) {
if (typeof name !== 'string') { throw new Error('constant name is not a string'); }
if ( name in constants ) { return constants[name]; }
else { throw new Error('constant ' + name + ' has not been defined'); }
};
}())
// ------------- demo ----------------------------
SETCONST( 'VAT', 0.175 );
alert( CONST('VAT') );
//try to alter the value of VAT
try{
SETCONST( 'VAT', 0.22 );
} catch ( exc ) {
alert (exc.message);
}
//check old value of VAT remains
alert( CONST('VAT') );
// try to get at constants object directly
constants['DODO'] = "dead bird"; // error
Mozillas MDN Web Docs包含了关于const的很好的例子和解释。摘录:
// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;
// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;
但遗憾的是,IE9/10仍然不支持const。荒谬的原因是:
IE9用const做什么?所以 到目前为止,我们的决定是不去 支持它。这还不是一个共识 功能,因为它从来没有可用 在所有浏览器上。 ... 最后,这似乎是最好的 网络的长期解决方案是 把它放在外面等着 标准化流程来运行它们 课程。
他们没有实现它是因为其他浏览器没有正确地实现它?!太害怕做得更好?标准定义与否,常量就是常量:设置一次,永不改变。
所有的想法:每个函数都可以被重写(XSS等)。所以var和function(){return}没有区别。Const是唯一真正的常量。
更新: IE11支持const:
IE11支持新兴的ECMAScript 6标准中定义良好且常用的特性,包括let、const、Map、Set和WeakMap,以及__proto__,以改进互操作性。
忘记IE,使用const关键字。
除了上面提到的,Rhino.js还实现了const。
好吧,这很难看,但它给了我一个在Firefox和Chromium中的常量,一个在Safari和Opera中的非常量(WTF?),以及一个在IE中的变量。
当然eval()是邪恶的,但是没有它,IE会抛出一个错误,阻止脚本运行。
Safari和Opera支持const关键字,但您可以更改const的值。
在本例中,服务器端代码将JavaScript写入页面,用一个值替换{0}。
try{
// i can haz const?
eval("const FOO='{0}';");
// for reals?
var original=FOO;
try{
FOO='?NO!';
}catch(err1){
// no err from Firefox/Chrome - fails silently
alert('err1 '+err1);
}
alert('const '+FOO);
if(FOO=='?NO!'){
// changed in Sf/Op - set back to original value
FOO=original;
}
}catch(err2){
// IE fail
alert('err2 '+err2);
// set var (no var keyword - Chrome/Firefox complain about redefining const)
FOO='{0}';
alert('var '+FOO);
}
alert('FOO '+FOO);
这有什么好处?没有太多,因为它不是跨浏览器的。在最好的情况下,至少有些浏览器不允许bookmarklet或第三方脚本修改该值,这可能会让人稍微安心一些。
通过Firefox 2,3,3.6, 4, Iron 8, Chrome 10,12, Opera 11, Safari 5, IE 6,9测试。