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

Ala*_*ALI 29 javascript

我最近阅读了关于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)

  • 有任何参考说明吗? (2认同)
  • @TechTurtle 我有点晚了,但只是为了完整起见:[这里](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) 是`const` 和 [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) 的引用是 `Object.freeze()` 的引用. (2认同)

Dan*_*tøl 7

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)


bur*_*kan 6

根据参考:

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/