Previous: Abstract Members, Up: Classes [Contents]
2.5 Method Proxies
'proxy [keywords] name': destmemberDeclare 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"
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.
- All arguments of proxy method
O.nameare forwarded todestmember.nameuntouched. - The return value provided by
destmember.nameis returned to the caller ofO.nameuntouched, except that- If
destmember.namereturnsdestmember(that is, returnsthis), it will be replaced withO; this ensures thatdestmemberremains encapsulated and preserves method chaining.
- If
- If
destmemberis not an object, calls toO.namewill immediately fail in error. - If
destmember.nameis not a function, calls toO.namewill immediately fail in error. - N.B.: Static method proxies are not yet supported.
Previous: Abstract Members, Up: Classes [Contents]