【问题标题】:Defining object as a Constant in Ecma-Script-6 [duplicate]在 Ecma-Script-6 中将对象定义为常量 [重复]
【发布时间】:2014-12-19 11:54:37
【问题描述】:

我有以下 Ecma-Script-6 模板常量的代码。

const person = 'John Smith';
console.log(person);

person = 'Naeem Shaikh';    
console.log("{{After changing the value for person.name}}");

console.log(person);

当然不行。 http://www.es6fiddle.net/i3vhumdx/ 出现以下错误,

person is read-only

现在我对一个对象做同样的事情。

const person = {name: 'John Smith'};

console.log(JSON.stringify(person));

person.name='Naeem Shaikh';
person.age="24";

console.log("{{After changing the value for person.name}}");

console.log(JSON.stringify(person));

http://www.es6fiddle.net/i3vhzblm/

输出是:

{"name":"John Smith"}
{{After changing the value for person.name}}
{"name":"Naeem Shaikh","age":"30"}

在这里我可以毫无问题地写入只读对象。谁能解释这种行为。

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:

    从函数内部更改传递给函数的参数时,您将具有相同的行为:如果它是一个字符串,则外部的不会更改,如果它是一个对象并且您更改了一个属性,它会被更改。

    关键是变量的值是什么:

    • 对于对象,它是对该对象的引用,您不要更改该引用
    • 对于字符串,它是对字符串的引用,恰好是不可变

    当您更改属性时,您不会更改值(对对象的引用)。

    the MDN 的摘录:

    // const also works on objects
    const myObject = {"key": "value"};
    
    // However, object attributes are not protected,
    // so the following statement is executed without problems
    myObject.key = "otherValue";
    

    您似乎想要的是拥有一个恒定的不可变对象。 Freeze它:

    const person = Object.freeze({name: 'John Smith'});
    

    这样就无法更改人名。

    【讨论】:

    • es6fiddle.net/i3vi7or9 我不会在这个小提琴中更改参考,对吧?但它就像一个常数
    • 您为 person 变量分配了一个新值:您试图让它引用另一个对象。
    • 好的,所以referencefreeze 是这里的关键词。具有引用值对象的Bcoz 与常量的行为会有些不同,为了克服它,我们应该冻结它。我现在得到了吗?
    • 我想你明白了。请注意(在更复杂的情况下)冻结不是递归的(当属性值的属性不是不可变时,它不会冻结它们)。
    • 知道了.. 谢谢你的好答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2012-06-10
    • 1970-01-01
    • 2016-07-16
    • 2019-04-07
    • 2016-07-13
    相关资源
    最近更新 更多