2017-04-18 25 views
0

即時學習JavaScript和即時通訊試圖瞭解的關鍵差異。 我可以使用Object.create(someName)創建對象,我可以使用 Object.create(someName.prototype)創建對象,但我不太瞭解關鍵區別。 我應該把屬性作爲常規屬性嗎? 像someName.asomeName.prototype.a? 它對我來說有點混亂。 我明白,當使用Object.Create即時定義我的對象原型鏈與對象即時指定,但我可以指定要麼someNamesomeName.prototype,但我似乎無法完全理解的差異和最佳做法。 非常感謝您的幫助。 :)Object.Create與Object.create(名稱)與Object.create(name.prototype)

+0

'someName'指的是一個對象,而'someName.prototype'指的是另一個對象,所以哪一個你應該使用Object.create()真的取決於你想要達到的目標。同樣,在'someName.a'或'someName.prototype.a'之間進行選擇取決於您想要實現的內容 - 如果您將屬性添加到原型,那麼具有該原型的* all *對象將有權訪問它,這是其他時間有助於幫助。 – nnnnnn

+0

非常感謝! –

回答

0

Object.create創建一個新對象,其原型是作爲整個函數的第一個參數傳遞的對象。

在JavaScript中,prototype屬性與特殊權力一個有規則的,但正如我已經說過,它仍然是一個常規對象

因此,何時與x或x.prototype一起去的問題取決於您的要求。

例如:

var obj = { name: "Matías" }; 

// This will create a new object whose prototype 
// is the object contained in the "obj" variable 
var obj2 = Object.create(obj); 

事實上,對象不擁有prototype屬性。您可以使用另一種方法,當你想創建一些構造函數的原型對象:

var A = function() {}; 
A.prototype.doStuff =() => { 
    // do stuff here 
}; 

// A common mistake is to provide A instead of A.prototype. 
// In JavaScript, even functions are objects, hence if you provide 
// A instead of A.prototype, the prototype of the newly created object 
// will be the function A and its members, not the ones that would be available 
// creating an object like this: new A() 
var B = Object.create(A.prototype); 
B.doStuff(); 

var C = Object.create(A); 
// Function "doStuff" is undefined!! 
C.doStuff(); 
+0

謝謝,現在更清楚:)! –