>我已经了解当方法驻留在父级的原型中时如何调用父的方法。但是,当父的方法不属于其原型时,有没有办法调用它的方法?
假设我们有以下示例:
(function () {
function Parent() {
this.myMethod2 = function(){
return 'Parent' + this.test;
};
}
Parent.prototype.myMethod = function () {
return 'Parent ' + this.test;
};
function Child() {
Parent.call(this);
this.myMethod = function(){
return 'Child >> ' + Parent.prototype.myMethod.call(this);
};
this.myMethod2 = function(){
return 'Child >> ' + Parent.myMethod2.call(this); // Uncaught TypeError: Cannot read property 'call' of undefined
};
}
var c = new Child();
c.test = 'test';
console.log(c.myMethod());
console.log(c.myMethod2());
})();
在这里,c.myMethod() 可以正常工作。
但是,c.myMethod2() 会导致错误"未捕获的类型错误:无法读取未定义的属性'调用'"
怎么样:
function Parent() {
this.myMethod2 = function(){
return 'Parent' + this.test;
};
}
function Child() {
Parent.call(this);
var old = this.myMethod2;
this.myMethod2 = function(){
return 'Child >> ' + old.apply(this, arguments);
};
}
解释:当你在一个字段中存储一个函数时;它的行为与普通对象完全一样,所以如果重新影响一个新值,你需要有一个对旧值的引用。当东西没有存储在原型中时,就会发生这种情况。
编辑:我在申请中添加了参数。Apply 具有能够调用将参数指定为数组的函数的功能。"参数"是一个预定义的名称,用于存储传递给当前函数的参数,对于 varargs 很有用,或者像这样重载。