How to call parent method from child

前提是你 提交于 2019-12-11 13:38:27

问题


I'm getting this error when I'm trying to call pranet method: 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:


You're not putting a "parentFunction" on the "Parent" prototype. Your "Parent" constructor adds a "parentFunction" property to the instance, but that won't be visible as a function on the prototype.

In a constructor function, this refers to the new instance that's been created as a result of calling via new. Adding methods to an instance is a fine thing to do, but it's not at all the same as adding methods to the constructor prototype.

If you want to access that "parentFunction" added by the "Parent" constructor, you can save a reference:

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


来源:https://stackoverflow.com/questions/27966786/how-to-call-parent-method-from-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!