简体   繁体   English

JavaScript有条件地覆盖类方法

[英]JavaScript override class method conditionally

I have a class that I have defined that I use all over my application. 我有一个我定义的类,我在我的应用程序中使用。 I have one page where I would like to change override some of the methods on all instances of the class. 我有一个页面,我想更改覆盖该类的所有实例上的一些方法。 Here is some code to illustrate. 这是一些代码来说明。

myclass-script.js MyClass的-的script.js

var MyClass = new Class({
    foo: function() {
        return 1;
    },

    bar: function() {
        return this.foo() + 9;
    },
});

change-myclass-script.js 变化MyClass的-的script.js

MyClass.implement({
    foo: function() {
        return this.parent() * -1;
    },
});

If I include on a page myclass-script.js I should see: 如果我在页面上包含myclass-script.js,我应该看到:

var test = new MyClass();
test.bar() === 10; //true

If I include myclass-script.js and then change-myclass-script.js I should see: 如果我包含myclass-script.js然后更改-myclass-script.js,我应该看到:

var test = new MyClass();
test.bar() === 8; //true

The issue I am having is that MyClass.implement applies to all instances of MyClass but it doesn't "override" the method, it replaces it. 我遇到的问题是MyClass.implement适用于MyClass的所有实例,但它没有“覆盖”该方法,它取代了它。 So the this.parent() call fails because there is no parent for that method. 所以this.parent()调用失败,因为该方法没有父级。 If I do MyClass.extend it does not apply like I want and I do not see the instances of MyClass calling the overridden method. 如果我做MyClass.extend它不适合我想要的,我没有看到MyClass的实例调用重写方法。

You could store the old version of foo, basically what Dimitar does: 您可以存储旧版本的foo,基本上是Dimitar所做的:

var foo = MyClass.prototype.foo;
MyClass.implement('foo', function(){
    return foo.call(this) * -1;
});

Or you can use Class.Refactor from MooTools More with the previous method: 或者您可以使用previous方法从MooTools More中使用Class.Refactor

Class.refactor(MyClass, {
    foo: function(){
        return this.previous() * -1;
    }
});

not sure if this is the best practice but it will allow you to run whatever logic you want or just return original method if not required... 不确定这是否是最好的做法,但它可以让你运行你想要的任何逻辑或只是返回原始方法,如果不需要...

var MyClass = new Class({
    foo: function() {
        return 1;
    },
    bar: function() {
        return this.foo() + 9;
    }
});

var f = new MyClass();
console.log(f.bar()); // 10

(function() {
    var orig = MyClass.prototype.foo;
    MyClass.prototype.foo = function() {
        return orig.apply(this, arguments) * -1; 
    };
})();

console.log(f.bar()); // 8

http://www.jsfiddle.net/dimitar/cXTrD/7/ http://www.jsfiddle.net/dimitar/cXTrD/7/

尝试执行以下操作:

MyClass.prototype.implement({

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM