gpt4 book ai didi

javascript - 为什么常数字段不 protected ?

转载 作者:行者123 更新时间:2023-12-02 15:51:22 25 4
gpt4 key购买 nike

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 只是将绑定(bind)声明为常量。它不会自动使其初始化的每个值都是不可变的。

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

关于javascript - 为什么常数字段不 protected ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31832748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com