2015-01-15 201 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