有没有办法在JavaScript 中使用常量?
如果不是,指定用作常量的变量的常见做法是什么?
有没有办法在JavaScript 中使用常量?
如果不是,指定用作常量的变量的常见做法是什么?
从ES2015 开始,JavaScript 有一个概念const
:
const MY_CONSTANT = "some-value";
这几乎适用于除 IE 8、9 和 10 之外的所有浏览器。有些可能还需要启用严格模式。
您可以使用var
ALL_CAPS 等约定来表明如果您需要支持旧浏览器或正在使用旧代码,则不应修改某些值:
var MY_CONSTANT = "some-value";
您是否试图保护变量不被修改?如果是这样,那么您可以使用module模式:
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() 方法:(。
如果您不需要严格保护变量值,那么只需按照建议进行操作并使用全部大写的约定。
该const
关键字在ECMAScript 6 草案中,但到目前为止它只享有少量浏览器支持:http : //kangax.github.io/compat-table/es6/。语法是:
const CONSTANT_NAME = 0;
"use strict";
var constants = Object.freeze({
"π": 3.141592653589793 ,
"e": 2.718281828459045 ,
"i": Math.sqrt(-1)
});
constants.π; // -> 3.141592653589793
constants.π = 3; // -> TypeError: Cannot assign to read only property 'π' …
constants.π; // -> 3.141592653589793
delete constants.π; // -> TypeError: Unable to delete property.
constants.π; // -> 3.141592653589793
请参阅Object.freeze。如果您想让参考成为只读,也可以使用const
constants
。
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>