JavaScript ES6`const a = {}`是可变的。为什么? [英] JavaScript ES6 `const a = {}` is mutable. Why?

查看:264
本文介绍了JavaScript ES6`const a = {}`是可变的。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript ES6,我很惊讶:

Using JavaScript ES6, I am surprised that doing:

const a = {};
a.foo = 'bar';
a.foo = 'car';

有效。为什么是这样?我会假定 const 意味着你不能更改 a 空对象并应用新的属性。更进一步的,我也假设你一旦设置,就不能改变一个属性的价值。

Is valid. Why is this? I would have assumed const would mean you cannot change the a empty object and apply new properties. Even further, I would also have assumed you cannot change the value of a property of a once it is set.

推荐答案

只有变量赋值是常数。引用的任何对象或数组保持不变。

Only the variable assignment is constant. Any objects or arrays referenced stay mutable.

const a = {one: 1};
a.three = 3; // this is ok.
a = {two: 2}; // this doesn't work.

你可以使用 Object。冻结

const a = {one: 1};
Object.freeze(a);
a.three = 3; // silently fails.
// a is still {one: 1} here.

这篇关于JavaScript ES6`const a = {}`是可变的。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆