我有一个JavaScript函数,它有一个静态变量:
function Constants() {
}
Constants.i = '1';现在,根据ECMA 6,我们有const关键字。使用它,我们可以使一个变量不可变。
我无法找到如何在函数静态变量中使用const关键字,如果我在下面使用,它没有加载函数:
const Constant.i = '1';如果任何人都能提出适当的方法来做同样的事情,那将是非常有帮助的。
发布于 2016-03-02 12:24:11
const只适用于变量,而不适用于对象(或函数)属性。
如前所述,可以使用Object.defineProperty定义不能更改的对象属性:
function Constants() {
}
Object.defineProperty(Constants, 'i', {
value: '1',
writable: false, // this prevents the property from being changed
enumerable: true, // this way, it shows up if you loop through the properties of Constants
configurable: false // this prevents the property from being deleted
});https://stackoverflow.com/questions/35746377
复制相似问题