为什么常量字段不受保护?

Why are the constant fields un-protected?

const可以用来声明常量:

> const a = 42
undefined
> a = 7
7
> a
42

这很酷,但我发现当使用 const 声明对象时,这种行为不再有效:

> const b = { foo: { bar: 42 }, baz: 7 }
undefined
> b.baz = { hello: "world" }
{ hello: 'world' }
> b.foo.bar = 7
7
> b
{ foo: { bar: 7 }, baz: { hello: 'world' } }

如您所见,我将 baz 字段修改为一个对象,并将 42 更改为 7

正在阅读 docs 我看到这是预期的:

// Overwriting the object fails as above (in Firefox and Chrome
but not in Safari)
MY_OBJECT = {"OTHER_KEY": "value"};

// However, object attributes are not protected,
// so the following statement is executed without problems
MY_OBJECT.key = "otherValue";

但是,为什么会这样呢?背后的逻辑是什么?

另一方面,问题是:如何声明常量对象?

However, why this is working like this? What is the logic behind?

const 只是将绑定声明为常量。它不会自动使它初始化的每个值都不可变。

how to declare constant objects?

要防止对象发生变异,您可以Object.freeze它:

"use strict";
const b = Object.freeze({foo: Object.freeze({bar: 42}), baz: 7});
b.baz = {hello: "world"}; // Error: Invalid assignment in strict mode