当我尝试调用 pranet 方法时出现此错误:Uncaught TypeError: Cannot read property 'call' of undefined
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/