在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
我的观点(只适用于对象)。
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;
其他回答
IE确实支持常量,比如:
<script language="VBScript">
Const IE_CONST = True
</script>
<script type="text/javascript">
if (typeof TEST_CONST == 'undefined') {
const IE_CONST = false;
}
alert(IE_CONST);
</script>
有一段时间,我在传递给with()语句的对象字面量中指定了“常量”(实际上仍然不是常量)。我觉得这很聪明。这里有一个例子:
with ({
MY_CONST : 'some really important value'
}) {
alert(MY_CONST);
}
在过去,我还创建了一个CONST名称空间,将所有常量放在其中。还有开销。天哪。
现在,我写var MY_CONST = 'whatever';吻。
声明一个只读命名的常量。 通过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
我在Greasemonkey脚本中使用const而不是var,但这是因为它们只会在Firefox上运行… 名称约定也确实是可行的方法(我两者都做!)
const关键字在javscript语言中可用,但不支持IE浏览器。其余所有浏览器支持。