2014-12-19 32 views
3

我對Ecma-Script-6模板常量有以下代碼。在Ecma-Script-6中定義對象爲常量

const person = 'John Smith'; 
console.log(person); 

person = 'Naeem Shaikh';  
console.log("{{After changing the value for person.name}}"); 

console.log(person); 

當然不起作用。 http://www.es6fiddle.net/i3vhumdx/它提供了以下錯誤,

person is read-only 

現在我做的對象同樣的事情。

const person = {name: 'John Smith'}; 

console.log(JSON.stringify(person)); 

person.name='Naeem Shaikh'; 
person.age="24"; 

console.log("{{After changing the value for person.name}}"); 

console.log(JSON.stringify(person)); 

http://www.es6fiddle.net/i3vhzblm/

輸出是:

{"name":"John Smith"} 
{{After changing the value for person.name}} 
{"name":"Naeem Shaikh","age":"30"} 

在這裏我能夠寫入只讀對象沒有任何問題。任何人都可以解釋此行爲。

回答

3

在更改從該函數內部傳遞給函數的參數時,您將具有相同的行爲:如果它是字符串,則外部函數不會更改,如果它是對象並且您更改屬性,則會更改該屬性。

的一點是什麼一個變量的值是:

  • 一個對象,它是對對象的引用,你不改變的字符串參考
  • ,這是一個參考字符串,這恰好是不變

當你改變的屬性,你不改變的值(參照對象)。

the MDN摘錄:

// const also works on objects 
const myObject = {"key": "value"}; 

// However, object attributes are not protected, 
// so the following statement is executed without problems 
myObject.key = "otherValue"; 

你似乎什麼想要的是具有恆定不變的對象Freeze它:

const person = Object.freeze({name: 'John Smith'}); 

這樣,它不可能改變人的名字。

+0

http://www.es6fiddle.net/i3vi7or9/我沒有改變這個參考在這個小提琴的權利?但它的工作原理類似於一個常量 – 2014-12-19 12:01:15

+0

您爲person變量指定一個新值:嘗試使其引用另一個對象。 – 2014-12-19 12:02:31

+0

好吧,所以'reference'和'freeze'是這裏的關鍵詞。具有參考值對象的Bcoz會表現爲一個常數有點不同,爲了克服它,我們應該凍結它。我現在明白嗎? – 2014-12-19 12:06:55