Previous: , Up: Classes   [Contents]

2.5 Method Proxies

'proxy [keywords] name': destmember

Declare a proxy method name, having optional additional keywords keywords, that invokes a method of the same name on object destmember and returns its result.

Method proxies help to eliminate boilerplate code for calling methods on an encapsulated object—a task that is very common with proxy and decorator design patterns.

var Pidgin = Class( 'Pidgin',
    'private _name': 'Flutter',

    'public cheep': function( chirp )
        return this._name + ": cheep " + chirp;

    'public rename': function( name )
        this._name = ''+name;
        return this;
} );

var IratePidginCheep = Class( 'IratePidginCheep',
    'private _pidgin': null,

    __construct: function( pidgin )
        this._pidgin = pidgin;

    // add our own method
    'public irateCheep': function( chirp )
        return this._pidgin.cheep( chirp ).toUpperCase();

    // retain original methods
    'proxy cheep':  '_pidgin',
    'proxy rename': '_pidgin',
} );

var irate = IratePidginCheep( Pidgin() );

irate.cheep( 'chirp' );
// "Flutter: cheep chirp"
irate.setName( 'Butter' ).cheep( 'chirp' );
// "Butter: cheep chirp"
irate.irateCheep( 'chop' );

Figure 2.37: Using the proxy keyword to proxy cheep and rename method calls to the object stored in property _pidgin.

Consider some object O whoose class uses method proxies.

Previous: , Up: Classes   [Contents]