2013-03-21 93 views
0

在嘗試瞭解Object.create時,我遇到了Object.create(): the New Way to Create Objects in JavaScript使用Object.create時無法通過setter設置對象屬性

從上面的頁面的一個例子:

var Car2 = Object.create(null); //this is an empty object, like {} 
Car2.prototype = { 
    getInfo: function() { 
    return 'A ' + this.color + ' ' + this.desc + '.'; 
    } 
}; 

var car2 = Object.create(Car2.prototype, { 
    //value properties 
    color: { writable: true, configurable:true, value: 'red' }, 
    //concrete desc value 
    rawDesc: { writable: false, configurable:true, value: 'Porsche boxter' }, 
    // data properties (assigned using getters and setters) 
    desc: { 
    configurable:true, 
    get: function()  { return this.rawDesc.toUpperCase(); }, 
    set: function (value) { this.rawDesc = value.toLowerCase(); } 
    } 
}); 
car2.color = 'blue'; 
alert(car2.getInfo()); //displays 'A blue PORSCHE BOXTER.' 

問:

  1. 如何正確的是上面的例子? This answer似乎與上述示例相矛盾。它似乎給了rawDesc可能是一個私人成員,只能通過desc的getter/setter修改的概念。這有用嗎?

  2. 此外,嘗試使用car2.desc = 'Merc'設置desc的值似乎不起作用。爲什麼?

  3. Object.defineProperty和Object.create的哪些部分是相似的?

研究:

有點相關的問題:Why can I set [enumerability and] writability of unconfigurable property descriptors? 我試圖消除writable: falsevalue: 'Porsche boxter',並試圖設定值,但無濟於事。

回答

0

一些評論:

var Car2 = Object.create(null); //this is an empty object, like {} 

的評論是不太正確的。 Car2(即其[[Prototype]])的內部原型將爲null,因此它不會繼承Object.prototype的任何屬性,而使用{}創建的對象則不會。

Car2.prototype = { 
    ... 
}; 

var car2 = Object.create(Car2.prototype, { 

看來毫無意義的創造Car2,因爲它不是一個函數,不能被用來作爲構造也沒有繼承任何的標準對象的方法。它只是分配給Car2.prototype的對象的佔位符。但我想這只是一個例子。

而對於問題...

如何正確的是上面的例子?這個答案似乎與上面的例子相矛盾。

它與示例矛盾嗎?

此外,嘗試使用car2.desc ='Merc'設置desc的值似乎不起作用。爲什麼?

因爲對於desc的setter實際上改變rawDesc,但rawDesc設置爲writeable: false。將其更改爲writeable: true並且值已更改。但無論如何這是一個公共財產,因此通過設置其他財產來設定其價值有點毫無意義。

Object.defineProperty和Object.create的哪些部分是相似的?

Object.createObject.defineProperty在ECMA-262中相鄰,不難解決。基本上,第一個只是將屬性添加到現有對象,第二個創建一個新對象並設置它的[[Prototype]](即它等同於構造函數)。

+0

謝謝,它確實是一個複製粘貼的例子,正如問題中提到的。至於與矛盾的例子,我想我誤解了'rawDesc'和desc是同一個屬性。只是乍一看,這個例子看起來提供了一種私有成員的方法,即在這種情況下,'rawDesc'只能通過'desc'來訪問。順便說一句@RobG任何機會,你都是同一個人(Rob Gravelle)寫這篇文章的同一個例子[這裏](http://www.htmlgoodies.com/beyond/javascript/object.create-the-new-way- to-create-objects-in-javascript.html)? – Siva 2013-03-21 10:16:05

+0

相應地更新了問題。 – Siva 2013-03-21 10:22:14

+0

@ Siva-no,那不是我。 – RobG 2013-03-21 14:16:31