2015-01-15 29 views
0

i was answering to a question where i encountered this problem在下面的代碼孩子的原型是如何被設置爲使用母公司的Object.create()method.I可以使用設置對象的原型使用的Object.create

child.prototype=new Parent(); 

做,但我想要做的它使用object.create。採用child.prototype =的Object.create(父)沒有原型設爲父

enter image description here

function Parent() { 
    this.parentFunction = function(){ 
     console.log('parentFunction'); 
    } 
} 
Parent.prototype.constructor = Parent; 

function Child() { 

    this.parentFunction = function() { 

     this.constructor.prototype.parentFunction.call(this); 
     console.log('parentFunction from child'); 
    } 
} 
Child.prototype = Object.create(Parent); 
Child.prototype.constructor = Child; 

var child = new Child(); 
console.dir(child); 
child.parentFunction(); 
+1

'Object.create'創建具有給定原型的新對象。你已經有了一個對象,你只是想改變它的原型,所以Object.create似乎是用來改變原型的錯誤方法。 – adeneo 2015-01-15 16:25:18

+0

'Child.prototype = Object.create(Parent.prototype);'。雖然這樣做沒有任何價值,因爲您沒有向「Parent.prototype」添加任何內容。還有其他的東西你錯過了。看看[繼承使用Object.create'的好處](http://stackoverflow.com/q/17392857/218196)。 – 2015-01-15 16:28:40

+0

@FelixKling謝謝!!但可以請您詳細說明!我還沒有定義父母的原型。陳述似乎令人困惑 – 2015-01-15 16:31:03

回答

0

Ť WO問題:

  1. 您定義的第一parentFunction是在構造函數Parent原型。所以Parent.prototype.parentFunction沒有定義。相反,有一個parentFunction的單獨副本,用於Parent的任何實例。

  2. Child的構造函數中,this.constructor.prototype指的是Child的原型,而不是Parent的原型。如果您需要Parent原型,可通過this.prototype.prototype訪問。

我最低限度修飾你的代碼,這樣對孩子呼籲parentFunction呼籲家長parentFunction

function Parent() { 

} 

Parent.prototype.parentFunction = function(){ 
     console.log('parentFunction in parent'); 
} 


Parent.prototype.constructor = Parent; 

function Child() { 

} 

Child.prototype = Object.create(Parent); 
Child.prototype.parentFunction = function() { 
     this.prototype.parentFunction.call(); 
     console.log('parentFunction from child'); 
}; 
Child.prototype.constructor = Child; 

var child = new Child(); 
console.dir(child); 
child.parentFunction(); 
+0

它和我的代碼一樣,但方式不同嗎?你能指出我爲什麼提供的代碼失敗嗎? – 2015-01-15 20:45:08

+1

當然。我在答覆的頂部解釋道。在你的代碼中,沒有'Parent'原型的'parentFunction',因爲你在構造函數中分配了'this'。 'this'是對當前對象的引用,*不是*原型,所以原型永遠不會被賦予'parentFunction'屬性。在我的版本中,我將屬性分配給原型。第二個問題是,訪問「Child」實例原型原型的代碼不正確:應該是this.prototype而不是this.construtor.prototype。 – 2015-01-15 21:27:29

相關問題