Previous: Abstract Members, 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' ); // "BUTTER: CHEEP CHOP"
Consider some object O
whoose class uses method proxies.
- All arguments of proxy method
O.name
are forwarded todestmember.name
untouched. - The return value provided by
destmember.name
is returned to the caller ofO.name
untouched, except that- If
destmember.name
returnsdestmember
(that is, returnsthis
), it will be replaced withO
; this ensures thatdestmember
remains encapsulated and preserves method chaining.
- If
- If
destmember
is not an object, calls toO.name
will immediately fail in error. - If
destmember.name
is not a function, calls toO.name
will immediately fail in error. - N.B.: Static method proxies are not yet supported.
Previous: Abstract Members, Up: Classes [Contents]