javascript - 如何从子调用父方法

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

最佳答案

您没有在“Parent”原型(prototype)上放置“parentFunction”。您的“Parent”构造函数将“parentFunction”属性添加到实例,但它不会作为函数在原型(prototype)上可见。

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

如果你想访问由“Parent”构造函数添加的那个“parentFunction”,你可以保存一个引用:

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

关于javascript - 如何从子调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27966786/

相关文章:

javascript - 访问和过滤在 Vue.js 组件的 <slot> 中定义的子组件

c# - 如何分离类和命名技术逻辑?

javascript - 如何在纯JS中通过包含元素顺序来对数组进行排序

c++ - 如何让对象相互通信?

javascript - 是否可以更新对象中包含的值

javascript - Mongoose/MongoDB 结果字段在 Javascript 中显示为未定义

javascript - 如何使用 jQuery 重置克隆对象的值?

javascript - 如何在 Angular js中的输入类型日期中显示日期?

javascript - Chart.js 图例对齐

c# - .Net 中 protected 内部是什么意思