为什么在使用JavaScript定义后可以更改对象const? [英] Why object const can be changed after definition in JavaScript?
问题描述
在JavaScript中:
In JavaScript:
const a = 6;
a = 2; // Error
const o = {};
o = 7; // Error
o.a = 5; // Good. Why?
const o = {a:1};
o.a = 2; // Good. Why?
我发现人们有时会定义const对象,但后来更改了它的值。为什么在定义后可以更改const?
I found people sometimes define a const object but later change its value. Why a const can be changed after its definition?
推荐答案
用 const $ c声明的变量$ c>表示一件事:独立变量名称以后不能用
=
重新分配。
A variable declared with const
means one thing: the standalone variable name cannot be reassigned with =
later.
相反, oa = 5;
并未重新分配变量名称-它是在改变对象的内容,但并未更改 o
变量指向内存中。
In contrast, o.a = 5;
is not reassigning the variable name - it's mutating the content of the object, but it's not changing what the o
variable points to in memory.
防止变量名重新分配 ,请使用 const
。要防止对象的变异是完全不同的-为此,您需要类似 Object.freeze
或使用 immutable-js 。
To prevent reassignment of a variable name, use const
. To prevent mutation of an object is something entirely different - for that, you'd need something like Object.freeze
or manipulate objects using immutable-js.
这篇关于为什么在使用JavaScript定义后可以更改对象const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!