我想在这里变聪明。假设我编写了一个包装其他类实例的类,重写了一个或两个方法,但将所有其他方法调用直接传递给委托(delegate)对象。
function Wrapper(delegate) {
this._delegate = delegate;
}
Wrapper.prototype.example = function() {
console.log('Doing something in wrapper');
this._delegate.example();
};
如果委托(delegate)有 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;
};
但如果可以避免的话,我宁愿不修改实例。
最佳答案
在 javascript 中扩展对象的一般方法不是按照您所做的方式包装它,然后要求您将每个方法调用转发给实际对象。因此,除非您有特定原因被迫这样做,否则最好只向现有对象添加新方法和属性。然后,所有现有的方法和属性都“正常工作”,而无需您做任何特别的事情。如果你想替换一些方法,你可以提供你自己的实现,但所有以前存在的方法将继续工作。
假设您有一个名为 foo
的现有对象,并且您想要重写一个名为 create()
的方法。你可以这样做:
foo.origCreate = foo.create;
foo.create = function(x, y) {
// do whatever you want here in the override
// including calling the origCreate method if you want
}
关于JavaScript 对象实例委托(delegate)/转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11953617/