我最近阅读了关于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
不会创建不可变的变量,而是创建不可变的绑定。
例如。
const temp1 = 1;
temp1 = 2 //error thrown here.
但
temp1.temp = 3 // no error here. Valid JS code as per ES6
所以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
let和const用于类型安全。没有必须使用它们的情况,但它们可以很方便并且难以发现错误。
一个例子,其中const对于您不想变成另一种类型的对象有用。
const x = {"hello":"world"};
// This is OK
x.hello = "stackoverflow";
// This is not OK
x = JSON.stringify(x);
根据this参考:
Costa用于制作无法重新分配新内容的变量。 “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);
你也可以尝试看看这个小提琴:https://jsfiddle.net/am2cbb00/1/
如果您使用对象并希望确保永远不会更改对象的标识,请说:
const a = {};
a.b = 1;
// ... somewhere in the other part of the code or from an async call
// suddenly
someAjaxCall().then(() => { a = null; }) // for preventing this
使用const
也是javascript编译器对你的代码进行优化的一个很好的提示,因此使用let
或var
使执行速度更快,因为身份永远不会改变,
但
因为性能原因要小心使用const / let in循环,因为它可能会因为每个循环创建一个变量而降低性能,但在大多数情况下差异可以忽略不计。
const
实际上创建了不可变的绑定,而不是使变量不可变。
由于原始数据类型(qazxsw poi,qazxsw poi,qazxsw poi,Boolean
和null
)是按值传递的,因此它们本身变为不可变的,因此无法重新分配给其他值。
在复杂数据类型(undefined
,String
和Number
)的情况下,它们通过引用传递。当我们更改或修改它们的属性/元素时,我们不会更改它们的绑定,因此Array
不会抛出任何错误。