繁体   English   中英

如何从子进程调用父方法

[英]How to call parent method from child

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

你没有在“父”原型上加上“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');
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM