2015-01-15 196 views
1

我得到當我試圖調用pranet方法這個錯誤調用父類的方法:Uncaught TypeError: Cannot read property 'call' of undefined如何從孩子

http://jsfiddle.net/5o7we3bd/

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

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

var child = new Child(); 
child.parentFunction(); 

回答

3

你不能把一個「parentFunction」上「父母」原型。您的「父級」構造函數將「parentFunction」屬性添加到實例,但這在原型上不會顯示爲函數。

在構造函數中,this引用通過new調用而創建的新實例。向一個實例添加方法是一件很好的事情,但它與爲構造函數原型添加方法完全不一樣。

如果你想訪問「parentFunction」由「父」的構造函數添加,可以保存一個參考:

function Child() { 
    Parent.call(this); 
    var oldParentFunction = this.parentFunction; 
    this.parentFunction = function() { 
     oldParentFunction.call(this); 
     console.log('parentFunction from child'); 
    } 
} 
+0

大。有用!非常感謝你的解釋。我是javascript OOP的新手。 – user1561346 2015-01-15 15:34:27