在Mootools中,我可以使用this.parent()
来调用父类中当前正在执行的方法:
foo: function() {
this.parent(); // Equals to super.foo() in Java
}
但是如果我想调用我在子类中覆盖的另一个父方法怎么办?
bar: function() {
// Overriden bar() method
},
foo: function() {
??? // Equals to super.bar() in Java
}
最佳答案
你仍然可以按照 javascript 来做
又名。
Super.prototype.foo.apply(this, args);
举个小例子
var Foo = new Class({
name: 'Foo',
foo: function(){
console.log(this.name, '=>foo');
},
baz: function(){
console.log('baz');
}
});
var Bar = new Class({
Extends: Foo,
name: 'Bar',
foo: function(){
console.log(this.name, '=>foo own');
this.parent();
},
bar: function(){
console.log(this.name, '=>bar');
// less DRY and knowledge, apply to my instance
this.$constructor.parent.prototype.foo.call(this);
// without applying to my instance... as static:
this.$constructor.parent.prototype.foo();
Foo.prototype.foo.apply(this); // normal JS way
}
});
var b = new Bar();
b.bar();
不是很好。不幸的是,它很糟糕。你可以使它成为一个 mixin,只从上游原型(prototype)调用任何方法,而不是依赖原型(prototype)链......
http://jsfiddle.net/dimitar/oraa1mgb/1/
var Super = new Class({
Super: function(method){
var superMethod = this.$constructor.parent.prototype[method],
args = Array.prototype.slice.call(arguments, 1);
if (!superMethod){
console.log('No ' + method + ' found or no parent proto');
return this;
}
else {
return superMethod.apply(this, args);
}
}
});
通过 Implements: [Super]
然后是 this.Super('foo', arg1, arg2)
。如果在父级上找不到它,你可以让它 return this[method](args)
。
这可能无法扩展到多个扩展类,它无法知道您真正指的是哪个父级 - 解析流程应该是自然的。
此外,如果您扩展了一个类并覆盖了一个方法,但仍然需要其他方法的原始方法,那么您可能做错了事情,同时可能违反了 LSP。
我会重构以表明 my.bar
与 parent.bar
之间的区别,例如,my.barClub
与 my.bar
或 parent.bar
,具有易于理解和维护的语义。您的本地方法将知道 bar
和 barClub
的存在,而父级只关心“普通”bar
。您可以通过子类中的条件确定调用哪个。
在您的本地 barClub
中,您还可以执行 this.bar()
,这将从 Super 调用。
照原样,可能很难遵循/理解/调试行为。善待 future 的自己:)
玩得开心
关于javascript - 如何在 Mootools 扩展类中调用任意父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27248406/