在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
我在Greasemonkey脚本中使用const而不是var,但这是因为它们只会在Firefox上运行… 名称约定也确实是可行的方法(我两者都做!)
其他回答
您可以轻松地为脚本配备一种用于常量的机制,这些常量可以设置但不能更改。试图更改它们将产生错误。
/* 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
然而,没有确切的跨浏览器预定义的方法来做到这一点,你可以通过控制变量的范围来实现,如其他答案所示。
但是我建议使用名称空间来区别于其他变量。这将使与其他变量的碰撞概率降到最低。
正确的命名空间
var iw_constant={
name:'sudhanshu',
age:'23'
//all varibale come like this
}
使用时,它会是iw_constant。name或iw_constant。age
你也可以使用Object.freeze方法阻止添加任何新键或改变iw_constant中的任何键。但是它不支持传统浏览器。
ex:
Object.freeze(iw_constant);
对于较老的浏览器,可以使用polyfill进行冻结方法。
如果你可以调用函数下面是最好的跨浏览器方式定义常量。将对象限定在一个自执行函数中,并为常量返回一个get函数 例:
var iw_constant= (function(){
var allConstant={
name:'sudhanshu',
age:'23'
//all varibale come like this
};
return function(key){
allConstant[key];
}
};
//获取值use Iw_constant ('name')或Iw_constant ('age')
**在这两个例子中,你必须非常注意名称间距,这样你的对象或函数不会被其他库替换。(如果对象或函数本身将被替换,则整个常量将消失)
const关键字在javscript语言中可用,但不支持IE浏览器。其余所有浏览器支持。
const关键字在ECMAScript 6草案中,但到目前为止它只获得了少量的浏览器支持:http://kangax.github.io/compat-table/es6/。语法为:
const CONSTANT_NAME = 0;
JavaScript ES6(重新)引入了所有主流浏览器都支持的const关键字。
通过const声明的变量不能被重新声明或重新赋值。
除此之外,const的行为类似于let。
对于基本数据类型(Boolean, Null, Undefined, Number, String, Symbol),它的行为与预期一样:
const x = 1;
x = 2;
console.log(x); // 1 ...as expected, re-assigning fails
注意:注意关于对象的陷阱:
const o = {x: 1};
o = {x: 2};
console.log(o); // {x: 1} ...as expected, re-assigning fails
o.x = 2;
console.log(o); // {x: 2} !!! const does not make objects immutable!
const a = [];
a = [1];
console.log(a); // 1 ...as expected, re-assigning fails
a.push(1);
console.log(a); // [1] !!! const does not make objects immutable
如果你真的需要一个不可变且绝对恒定的对象:只需使用const ALL_CAPS来明确你的意图。无论如何,对于所有const声明来说,这都是一个很好的约定,所以只需依赖它即可。