JavaScript overrides class method conditionally

I have a class that I defined, which I use throughout my application. I have one page where I would like to change override some methods in all instances of the class. Here is some code to illustrate.

myclass- script.js

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

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

changes-myclass- script.js

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

If I include the myclass- script.js page, I should see:

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

If I include myclass- script.js and then change-myclass- script.js, I should see:

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

, , , MyClass.implement MyClass, "" , . this.parent() , . MyClass.extend, , , MyClass, .

+3
3

foo, , Dimitar:

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

Class.Refactor MooTools More previous:

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

, , , , , ...

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/

+2

Try the following:

MyClass.prototype.implement({
-1
source

Source: https://habr.com/ru/post/1787233/


All Articles