在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
在JavaScript中,我倾向于使用函数返回常量值。
function MY_CONSTANT() {
return "some-value";
}
alert(MY_CONSTANT());
其他回答
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声明来说,这都是一个很好的约定,所以只需依赖它即可。
我的观点(只适用于对象)。
var constants = (function(){
var a = 9;
//GLOBAL CONSTANT (through "return")
window.__defineGetter__("GCONST", function(){
return a;
});
//LOCAL CONSTANT
return {
get CONST(){
return a;
}
}
})();
constants.CONST = 8; //9
alert(constants.CONST); //9
试试!但是要明白,这是对象,而不是简单的变量。
还可以试试:
const a = 9;
您是否试图保护变量不被修改?如果是,那么你可以使用模块模式:
var CONFIG = (function() {
var private = {
'MY_CONST': '1',
'ANOTHER_CONST': '2'
};
return {
get: function(name) { return private[name]; }
};
})();
alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1
CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1
CONFIG.private.MY_CONST = '2'; // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1
使用这种方法,不能修改值。但是,你必须在CONFIG:(上使用get()方法。
如果您不需要严格保护变量值,那么只需按照建议执行并使用ALL CAPS约定即可。
声明一个只读命名的常量。 通过const声明的变量不能被重新声明或重新赋值。 常量可以用大写或小写来声明,但通用的 惯例是全部使用大写字母。
// const c;
// c = 9; //intialization and declearation at same place
const c = 9;
// const c = 9;// re-declare and initialization is not possible
console.log(c);//9
忘记IE,使用const关键字。