我最近阅读了关于ES6 const关键字的内容,我可以理解它在这样的事情时的重要性:
(function(){
const PI = 3.14;
PI = 3.15; // Uncaught TypeError: Assignment to constant variable
})();
Run Code Online (Sandbox Code Playgroud)
所以,没有人可以改变我的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}
})();
Run Code Online (Sandbox Code Playgroud)
因此,当声明一个对象时:我该说什么时候:现在我必须声明我的对象const?
She*_*kaj 53
它是围绕Web的常见误解,CONST不会创建不可变变量而是创建不可变绑定.
例如.
const temp1 = 1;
temp1 = 2 //error thrown here.
Run Code Online (Sandbox Code Playgroud)
但
temp1.temp = 3 // no error here. Valid JS code as per ES6
Run Code Online (Sandbox Code Playgroud)
因此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
Run Code Online (Sandbox Code Playgroud)
let和const用于类型安全。没有任何情况下,你必须使用他们,但他们都能得心应手,并降低很难发现的bug。
一个实例的例子,其中const对于您不想变成另一种类型的对象很有用。
const x = {"hello":"world"};
// This is OK
x.hello = "stackoverflow";
// This is not OK
x = JSON.stringify(x);
Run Code Online (Sandbox Code Playgroud)
根据此参考:
Costant用于创建无法重新分配新内容的变量。“ const”关键字使变量本身不可变,而不是其分配的内容(例如,如果内容是对象,则意味着对象本身仍可以更改)。
这意味着可以更改分配给const变量的对象的内容,但是不能为该const变量分配新的对象。
还允许您向对象添加一些新属性。
const myVar = "someValue";
const myObj = {"name": "nameValue", "age": 14}
console.log(myVar); //someValue
console.log(myObj.name); //nameValue
myObj.name = "newNameValue";
console.log(myObj.name); //newNameValue
myObj.someNewAttr = "newAttrValue";
console.log(myObj.someNewAttr); //newAttrValue
myObj = {"newNameAttr": "newNameValue"}; //Uncaught TypeError: Assignment to constant variable.
console.log(myObj.newNameAttr);
myVar = "newValue"; //Uncaught TypeError: Assignment to constant variable.
console.log(myVar);
Run Code Online (Sandbox Code Playgroud)
您也可以尝试看看这个小提琴:https : //jsfiddle.net/am2cbb00/1/
| 归档时间: |
|
| 查看次数: |
24522 次 |
| 最近记录: |