在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
您可以轻松地为脚本配备一种用于常量的机制,这些常量可以设置但不能更改。试图更改它们将产生错误。
/* 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
其他回答
伯克的答案的改进版本,让你做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;
}());
*属性是只读的,只有初始值是不可变的。
const关键字在javscript语言中可用,但不支持IE浏览器。其余所有浏览器支持。
不,不一般。Firefox实现了const,但我知道IE没有。
@John指出了const的一个常用命名实践,在其他语言中已经使用了很多年,我看不出为什么你不能使用它。当然,这并不意味着有人不会重写变量的值。:)
在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"时,你马上就明白了。
除了上面提到的,Rhino.js还实现了const。