我最近读到了有关 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}
})();
所以当声明一个对象时:我什么时候应该说:现在我must声明我的对象const
?
这是网络上常见的误解,CONST
不会创建不可变变量,而是创建不可变绑定。
eg.
const temp1 = 1;
temp1 = 2 //error thrown here.
But
temp1.temp = 3 // no error here. Valid JS code as per ES6
so const
创建到该特定对象的绑定。 const 确保变量temp1
不会有任何其他对象的绑定。
现在来到Object
。我们可以得到不可变的特征Object
通过使用Object.freeze
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)