什么时候在 JavaScript 中对对象使用 const ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44604212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:38:40  来源:igfitidea点击:

When to use const with objects in JavaScript?

javascript

提问by Ala Eddine JEBALI

I recently read about ES6 constkeyword and I can understand its importance when having something like this:

我最近阅读了有关 ES6const关键字的信息,当我遇到这样的事情时,我可以理解它的重要性:

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

So, nobody can change my PIvariable.

所以,没有人可以改变我的PI变量。

The misunderstanding I have is that I don't understand in which situation the use of constwith objects can make sense (other than preventing people to do myObj = newValue;).

我的误解是我不明白在哪种情况下使用constwith 对象有意义(除了阻止人们做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}
})();

So when declaring an object: when should I say: Now I mustdeclare my object with const?

所以在声明一个对象时:我什么时候应该说:现在我必须const?

回答by Shekhar Pankaj

it is a common misconception around the web, CONSTdoesn't creates immutable variables instead it creates immutable binding.

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

eg.

例如。

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

But

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

so constcreates a binding to that particular object. const assures that variable temp1won't have any other object's Binding.

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

Now coming to Object. we can get immutable feature with Objectby using Object.freeze

现在来到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

回答by burakhan alkan

According to the thisreference:

根据这个参考:

Costants are used to make variables which cannot be re-assigned new content. "const" keyword makes variable itself immutable, not its assigned content (for instance, in case the content is an object, this means the object itself can still be altered).

常量用于创建不能重新分配新内容的变量。“const”关键字使变量本身不可变,而不是其分配的内容(例如,如果内容是对象,这意味着对象本身仍然可以更改)。

That means it's possible to change content of the object which assigned to const variable but you cannot assign a new object this const variable.

这意味着可以更改分配给 const 变量的对象的内容,但不能将此 const 变量分配给新对象。

You are also allowed to add some new attribute to your object.

您还可以向对象添加一些新属性。

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);

You can also try and see on this fiddle: https://jsfiddle.net/am2cbb00/1/

你也可以试试看这个小提琴:https: //jsfiddle.net/am2cbb00/1/

回答by Daniel Vest?l

let and const are meant for type safety. There is no situation where you mustuse them, but they can be handy and reduce hard to spot bugs.

let 和 const 用于类型安全。在任何情况下都必须使用它们,但它们很方便并减少难以发现的错误。

One example of a situation where const would be useful for an object that you don't want to turn into another type.

const 对您不想变成另一种类型的对象有用的情况的一个示例。

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

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

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

回答by Karen Grigoryan

If you work with an object and want to make sure that identity of the object is never changed say:

如果您使用一个对象并希望确保该对象的身份永远不会改变,请说:

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

Also using constis a good hint for javascript compiler to make optimisations about your code, thus making execution much faster then with letor varbecause the identity never changes,

const对于 javascript 编译器来说,使用也是一个很好的提示,可以对您的代码进行优化,从而使执行速度更快,let或者var因为身份永远不会改变,

BUT

beware of using const/let in loops for performance reasons, because it might slowdown the performance due to creation of a variable per loop, but in most cases the difference is negligible.

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

回答by Jaspreet Singh

constactually creates immutable binding instead of making the variables immutable.

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

Since primitive data-types (Boolean, null, undefined, String, and Number) are passed by value, they themselves become immutable and hence can't be re-assigned to some other value.

由于原始数据类型(BooleannullundefinedStringNumber)是按值传递的,因此它们本身变得不可变,因此不能重新分配给其他值。

In the case of complex data-types (Array, Function, and Object), they are passed by reference. When we change or modify their properties/elements, we not changing their binding, hence constdoesn't throw any error.

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