Overriding/Extending the Magento core javascript files
See this from prototype manual http://prototypejs.org/doc/latest/language/Function/prototype/wrap/ you can wrap whatever object method and even call "parent" if needed and here's a pseudo sample:
//where Product.Config is the object/class you need to "override"
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod){
//replace the original method here with your own stuff
//or call parentMethod(); if conditions don't match
});
Just to add to @anton-s's absolutely correct answer, you can also do "full" class rewrites:
// Create the original class
var ClassA = Class.create();
ClassA.prototype = {
initialize: function(config) {
this.config = config;
},
test: function(msg) {
console.log('Hi from class A with message ' + msg);
}
};
// Create new class extending the original class
var ClassB = Class.create(ClassA, {
// $super is a reference to the original method
test: function($super, msg) {
console.log('Hi from class B');
console.log('this.config is accessible in class B: ' + this.config);
$super(msg + ' ...')
}
});
// To make the extend an override, you can do this:
ClassA = ClassB;
// ClassA now is ClassB overriding the original ClassA
var a = new ClassA('some config data');
a.test('Call A 1');
Since all this only works on prototype classes, not on already instantiated objects, I'll also throw in this hack, which is pretty much what wrap() does, too:
// Overriding a method of an already instantiated object
// There are many ways to do this more elegantly thanks to the amazing JS scoping magic
a.origTest = a.test;
a.test = function(msg) {
console.log('Hi from the patched method');
this.origTest(msg);
}
a.test('Call A 2');
Keep in mind though that the wrap()
method is nicer, and can also be used on on class definitions or on concrete instances.
// Wrap method of concrete instance
spConfig.getOptionLabel = spConfig.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
// Wrap method of class declaration
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});