如何在 Mootools 扩展类中调用任意父方法

How to invoke an arbitrary parent method in a Mootools extended Class

本文关键字:调用 任意父 方法 扩展 Mootools      更新时间:2023-09-26

在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();

不是很好。不幸的是,它很糟糕。你可以把它作为一个混合,只从上游 proto 调用任何方法,而不是依赖 proto 链......

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.barparent.bar之间的区别,例如,my.barClub vs my.barparent.bar,具有语义含义,易于理解和维护。 您的本地方法将知道barbarClub的存在,而父方法只关心"正常"bar。 您可以从子类中通过条件确定要调用哪个。

在您当地的barClub您也可以做this.bar(),这将从超级呼叫。

照原样,可能很难遵循/理解/调试行为。 善待未来的自己:)

玩得愉快