JavaScript Object instance delegation/forwarding

Viewed 1640

I'm trying to get clever here. Lets say I write a class that wraps an instance of some other class, overriding one or two methods, but passing all other method calls straight through to the delegate object.

function Wrapper(delegate) {
  this._delegate = delegate;
}

Wrapper.prototype.example = function() {
  console.log('Doing something in wrapper');
  this._delegate.example();
};

If the delegate has 100 other methods (exaggeration, granted), far from defining a method for each of them in my Wrapper, is there an elegant way to do this in JavaScript?

I've considered just method swizzling/proxying on the actual instance, i.e.

Wrapper.wrap = function(delegate) {
    var example = delegate.example;
    delegate.example = function() {
      example.call(this, arguments);
      console.log('Forwarded an overridden method call!');
    };
    return delegate;
};

But I'd rather not modify the instance, if I can avoid it.

1 Answers
Related