我想从 [Child].g()
内部调用 [Parent].f()
而不是 [Child].f()
.
假设我有 MooTools 代码:
var Parent = new Class({
f: function () {
console.log('Parent.f()');
}
});
var Child = new Class({
Extends: Parent,
f: function () {
console.log('Child.f()');
},
g: function () {
// Call Parent.f()
this.parent.f();
}
});
var o = new Child();
o.g();
显然 this.parent.f()
是无意义的,因为 MooTools 使 this.parent
成为父类的方法,其名称与您所在的方法相同,即在 Child.g()
中,这将是 Parent.g()
。
那么,我如何调用 P.f()
?
最佳答案
您遇到的问题是 Child
hasOwnProperty
f
,因此调用 child.f()
将得到它在实例上而不是原型(prototype)上。
而不是像另一个答案中建议的那样通过切换 this.$caller.$name
进行破解,只需从父原型(prototype)直接调用它即可:
this.$constructor.parent.prototype.f.call(this);
// or
this.$constructor.parent.prototype.f.apply(this, arguments);
当然,如果你不关心Reflection-ish,你可以只执行P.prototype.f.call(this)
- 但它是非DRY,因为它意味着方法需要知道 super 的名字。
这种方法的问题是,如果父级正在扩展另一个父级等等,它是否会起作用,但对于大多数情况来说应该没问题。如果 Child 没有父级或没有 f
,它也会失败,从逻辑上讲,它应该恢复运行自己的 f
实现。
var Parent = new Class({
f: function(msg){
console.log('Parent.f() says ' + msg);
}
});
var Child = new Class({
Extends: Parent,
f: function(){
console.log('Child.f()');
},
g: function(){
// Call Parent.f()
this.$constructor.parent.prototype.f.apply(this, arguments);
}
});
new Child().g('hello');
如果您需要经常这样做,您可以在父类上创建一个新方法作为 mixin。例如。
Class.parenting = new Class({
// mixin class that allows call
_parent: function(method, args){
this.$constructor.parent.prototype[method].apply(this, args);
}.protect() // private, restricted to methods
});
var Parent = new Class({
Implements: [Class.parenting],
f: function(msg){
console.log('Parent.f() says ' + msg);
}
});
var Child = new Class({
Extends: Parent,
f: function(){
console.log('Child.f()');
},
g: function(){
this._parent('f', arguments);
}
});
var c = new Child();
c.g('hello');
c._parent('f'); // throws, only instances methods can call this
关于javascript - 如何调用与我所在的名称不同的父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19997722/