你仍然可以做到这一点按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调用从上游的原只而不是依赖于原型链中的任何方法...
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冲突。
我重构指示VS my.bar
或parent.bar
my.bar
VS parent.bar
,例如,my.barClub
之间的差异,具有语义含义是明确的理解和维护。您的当地方法将知道bar
和barClub
的存在,而父母只会关心“正常”bar
。您可以通过您的子类中的条件来确定要调用哪一个。
在您的本地barClub
你也可以做这将从超级电话。
原样,可能很难跟踪/理解/调试行为。善待你的未来自我:)
玩得开心
太棒了!正常的JS方式看起来不错,反正非常感谢你的mixin。 – 2014-12-02 13:44:55