首页 > 解决方案 > 使用这种 JavaScript 代码有什么缺点吗?

问题描述

考虑以下 JavaScript 代码:

const myObject = {
   innerValue: 'test'
}

myObject.innerValue = 'I can still change this, this is not a constant';

如果我运行这段代码,我想浏览器不会输出任何错误,因为只有外部对象myObject是常量,而它的属性不是。但是这段 JavaScript 代码的有效性如何?我的意思是,写这样的东西有什么负面的缺点吗?

标签: 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);


推荐阅读