如何从子方法调用父方法

How to call parent method from child

本文关键字:方法 调用 子方法      更新时间:2023-09-26

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

你没有在"Parent"原型上放置"parentFunction"。您的"父"构造函数将"parentFunction"属性添加到实例,但该属性在原型上不会作为函数可见。

在构造函数中,this是指由于通过 new 调用而创建的新实例。向实例添加方法是一件好事,但它与向构造函数原型添加方法完全不同。

如果要访问由"Parent"构造函数添加的"parentFunction",可以保存引用:

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