考虑以下JavaScript代码:
const myObject = {
innerValue: 'test'
}
myObject.innerValue = 'I can still change this, this is not a constant';
我想如果我运行这段代码,浏览器不会输出任何错误,因为只有外部对象myObject
是一个常量,而其属性不是。但是此JavaScript代码的有效性如何?我的意思是,编写这样的内容是否有负面影响?
看起来您已经了解了该变量myObject
是const,但它所引用的对象却不是。这很大程度上是JavaScript设计的。使用const
以前的方法并不能防止您修改对象。
您可以使用属性来保护的值innerValue
。
const myObject = {};
Object.defineProperty(myObject, 'innerValue', {
value: 'test',
writable: false
});
console.log(myObject.innerValue);
myObject.innerValue = 'this is not an error but will not change the value';
console.log(myObject.innerValue);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句