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
var MyClass = new Class({
foo: function() {
return 1;
},
bar: function() {
return this.foo() + 9;
},
});
change-myclass-script.js
MyClass.implement({
foo: function() {
return this.parent() * -1;
},
});
If I include on a page myclass-script.js 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
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. So the this.parent() call fails because there is no parent for that method. 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.
You could store the old version of foo, basically what Dimitar does:
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:
Class.refactor(MyClass, {
foo: function(){
return this.previous() * -1;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With