我想在这里变得聪明。假设我编写了一个类,它包装了某个其他类的实例,覆盖了一个或两个方法,但将所有其他方法调用直接传递给了委托对象。
function Wrapper(delegate) {
this._delegate = delegate;
}
Wrapper.prototype.example = function() {
console.log('Doing something in wrapper');
this._delegate.example();
};
如果委托有 100 个其他方法(夸大,授予),远没有在我的 Wrapper 中为每个方法定义一个方法,那么在 JavaScript 中是否有一种优雅的方法来做到这一点?
我只考虑了实际实例上的方法调配/代理,即
Wrapper.wrap = function(delegate) {
var example = delegate.example;
delegate.example = function() {
example.call(this, arguments);
console.log('Forwarded an overridden method call!');
};
return delegate;
};
但如果可以避免的话,我宁愿不修改实例。