补充@anton-s绝对正确的答案,你还可以进行“完整的”类重写:
var ClassA = Class.create();
ClassA.prototype = {
initialize: function(config) {
this.config = config;
},
test: function(msg) {
console.log('Hi from class A with message ' + msg);
}
};
var ClassB = Class.create(ClassA, {
test: function($super, msg) {
console.log('Hi from class B');
console.log('this.config is accessible in class B: ' + this.config);
$super(msg + ' ...')
}
});
ClassA = ClassB;
var a = new ClassA('some config data');
a.test('Call A 1');
因为所有这些仅适用于原型类,而不是已实例化的对象,我还会提供这个hack,它几乎就是wrap()所做的事情:
a.origTest = a.test;
a.test = function(msg) {
console.log('Hi from the patched method');
this.origTest(msg);
}
a.test('Call A 2');
请记住,wrap()
方法更加优雅,并且也可以用于类定义或具体实例。
spConfig.getOptionLabel = spConfig.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});