如何从子进程调用父方法

时间:2015-01-15 15:22:51

标签: javascript oop javascript-objects

当我尝试调用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();

1 个答案:

答案 0 :(得分: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');
   }
}
相关问题