如何从子级调用父级方法 [英] How to call parent method from child

查看:75
本文介绍了如何从子级调用父级方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试调用pranet方法时出现此错误:Uncaught TypeError: Cannot read property 'call' of undefined

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();

推荐答案

您没有在父母"原型上放置"parentFunction".您的父代"构造函数为 instance 添加了"parentFunction"属性,但是在原型上该函数将不可见.

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.

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

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.

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

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');
   }
}

这篇关于如何从子级调用父级方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆