gpt4 book ai didi

javascript - 如何调用与我所在的名称不同的父方法?

转载 作者:行者123 更新时间:2023-11-29 19:45:34 24 4
gpt4 key购买 nike

我想从 [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 的名字。

这种方法的问题在于,如果 Parent 正在扩展另一个 parent 等等,它是否会起作用,但对于大多数情况来说应该没问题。如果 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');

如果您需要经常这样做,您可以在父类上创建一个新方法作为混合。例如。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com