javascript - 使用这种 JavaScript 代码有什么缺点吗?
问题描述
考虑以下 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);
推荐阅读
- ms-access - 为什么 MS Access 中连续表单标题中的标签不可点击?
- python - 在另一个模型中使用模型预测
- android - 使用改造使用 API 时获取“null”?
- python - vscode 文档字符串没有正确显示
- arduino - 关于HC-SR04的测距能力
- validation - 如果我们先扩充数据然后随机选择数据然后拆分数据可以吗?
- php - WordPress/Timber 后循环循环四次
- opencv - USB 网络摄像头在树莓派上拍照太慢
- bash - 将文件的一部分替换为当前目录的路径
- html - iOS Safari中导航栏溢出滚动容器底部“截止”