问题
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();
回答1:
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.
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.
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');
}
}
来源:https://stackoverflow.com/questions/27966786/how-to-call-parent-method-from-child