何时在JavaScript中使用const与对象?

问题描述 投票:21回答:5

我最近阅读了关于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声明我的对象?

javascript
5个回答
43
投票

这是一个围绕网络的常见误解,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

6
投票

let和const用于类型安全。没有必须使用它们的情况,但它们可以很方便并且难以发现错误。

一个例子,其中const对于您不想变成另一种类型的对象有用。

const x = {"hello":"world"};

// This is OK
x.hello = "stackoverflow";

// This is not OK
x = JSON.stringify(x);

5
投票

根据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/


2
投票

如果您使用对象并希望确保永远不会更改对象的标识,请说:

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编译器对你的代码进行优化的一个很好的提示,因此使用letvar使执行速度更快,因为身份永远不会改变,

因为性能原因要小心使用const / let in循环,因为它可能会因为每个循环创建一个变量而降低性能,但在大多数情况下差异可以忽略不计。


1
投票

const实际上创建了不可变的绑定,而不是使变量不可变。

由于原始数据类型(qazxsw poi,qazxsw poi,qazxsw poi,Booleannull)是按值传递的,因此它们本身变为不可变的,因此无法重新分配给其他值。

在复杂数据类型(undefinedStringNumber)的情况下,它们通过引用传递。当我们更改或修改它们的属性/元素时,我们不会更改它们的绑定,因此Array不会抛出任何错误。

© www.soinside.com 2019 - 2024. All rights reserved.