2017-06-17 99 views
9

我最近讀到ES6 const關鍵字,並具有這樣的事情時,我能理解它的重要性:何時在JavaScript中使用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

回答

12

它是網絡上一種常見的誤解,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.freeze

const temp3 = Object.freeze({a:3,b:4}) 
temp.a =2 // it wont update the value of a, it still have 3 
temp3.c = 6 // still valid but wont change the object 
+0

謝謝你的明確答案。你能解釋一下「'const'如何確保變量'temp1'不會有任何其他對象的綁定。」? –

+0

任何參考文獻說明? – TechTurtle

+0

@TechTurtle,在瀏覽器的控制檯中執行上面的例子 –

-1

如果您不希望更改其值,則將Object聲明爲const。所以這個對象是隻讀的。在ES6多變的對象被創建讓

let x = {asdf: 1} 
+0

即使你使用'const',對象不會成爲「只讀」得與Object不可改變的特徵。您仍然可以更改其屬性。 爲了使對象不可變,你必須使用:Object.freeze。乾杯! – ValentinVoilean

+0

對於像String或Number這樣的簡單類型來說,這僅僅是部分正確的,因爲const使它只讀,但是Array或Object需要被凍結爲只讀。一個常量的數組不能改變爲一個對象或一個簡單的類型,但可以添加新的條目。 –

0

如果與對象的工作,並希望確保該對象的身份從來沒有改變過說:

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因爲身份永不改變,

BUT

由於性能方面的原因,要小心在循環中使用const,因爲它實際上會由於每個循環創建一個變量而降低性能。

1

按照this參考:

Costants被用來製造不能被重新分配新的內容變量。 「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/

1

讓和const都是爲了類型安全。您不需要使用必須使用,但它們可以很方便並且很難找到錯誤。

一種情況的例子,其中const對於不想變成另一種類型的對象有用。

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

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

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