gpt4 book ai didi

javascript - 何时在 JavaScript 中对对象使用 const?

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

我最近读到了有关 ES6 const 关键字的内容,当我遇到这样的事情时,我可以理解它的重要性:

(function(){
const PI = 3.14;
PI = 3.15; // Uncaught TypeError: Assignment to constant variable
})();

因此,没有人可以更改我的 PI 变量。

我的误解是,我不明白在哪种情况下对对象使用 const 才有意义(除了阻止人们执行 myObj = newValue; 操作) >).

(function(){
const obj = {a:1 ,b: 2, c:3};
//obj = {x:7 , y:8, z: 9}
//This is good
//TypeError: Assignment to constant variable.

obj.a=7; obj.b=8 ; obj.c=9;
console.log(obj); //outputs: {a: 7, b: 8, c: 9}
})();

因此,在声明对象时:我什么时候应该说:现在我必须使用const声明我的对象?

最佳答案

这是网络上的一个常见误解,CONST 不会创建不可变变量,而是创建不可变绑定(bind)。

例如。

 const temp1 = 1;
temp1 = 2 //error thrown here.

但是

 temp1.temp = 3 // no error here. Valid JS code as per ES6

so const 创建到该特定对象的绑定(bind)。 const 确保变量 temp1 不会有任何其他对象的绑定(bind)。

现在来到对象。我们可以通过使用 Object.freeze

获得 Object 的不可变特性
const temp3 = Object.freeze( {a:3,b:4})
temp3.a = 2 // it wont update the value of a, it still have 3
temp3.c = 6 // still valid but wont change the object

关于javascript - 何时在 JavaScript 中对对象使用 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44604212/

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