d11wtq d11wtq - 2 years ago 90
Javascript Question

JavaScript Object instance delegation/forwarding

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');

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.

Answer Source

The general way of extending an object in javascript is not by wrapping it the way you've done which then requires you to forward every method call to the actual object. So, unless you have a specific reason for being forced to do it that way, it's much better to just add new methods and properties to the existing object. Then, all the existing methods and properties "just work" without you having to do anything special. If you want to replace some method, you can supply your own implementation, but all previously existing methods will just continue to work.

Let's say you have an existing object called foo and you want to override one method named create() on it. You can do that like this:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download