在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
ECMAScript 5引入了Object.defineProperty:
Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false });
每个现代浏览器(以及IE≥9)都支持它。
参见:Object.defineProperty在ES5?
其他回答
如果你不介意使用函数:
var constant = function(val) {
return function() {
return val;
}
}
这种方法为您提供函数而不是常规变量,但它保证一旦设置了值,就没有人可以更改值。
a = constant(10);
a(); // 10
b = constant(20);
b(); // 20
我个人觉得这相当令人愉快,特别是在我已经习惯了这种模式之后。
*除非有人在你调用函数常量之前重新定义了它
const关键字在javscript语言中可用,但不支持IE浏览器。其余所有浏览器支持。
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__,以改进互操作性。
您可以轻松地为脚本配备一种用于常量的机制,这些常量可以设置但不能更改。试图更改它们将产生错误。
/* 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
在JavaScript中,我的实践是尽可能避免常量,而是使用字符串。当你想要向外界公开你的常量时,常量的问题就出现了:
例如,可以实现以下Date API:
date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)
但如果简单地写成:
date.add(5, "days").add(12, "hours")
这样,“天”和“小时”就像常数一样,因为你无法从外部改变“小时”代表的秒数。但是很容易覆盖MyModule.Date.HOUR。
这种方法还有助于调试。如果Firebug告诉你action === 18,你很难理解它的意思,但是当你看到action === "save"时,你马上就明白了。