为什么在使用JavaScript定义后可以更改对象const? [英] Why object const can be changed after definition in JavaScript?

查看:120
本文介绍了为什么在使用JavaScript定义后可以更改对象const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 表示一件事独立变量名称以后不能用 = 重新分配。

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屋!

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