There is a noSuchMethod feature in some javascript implementations (Rhino, SpiderMonkey)
proxy = {
__noSuchMethod__: function(methodName, args){
return "The " + methodName + " method isn't implemented yet. HINT: I accept cash and beer bribes" ;
},
realMethod: function(){
return "implemented" ;
}
}
js> proxy.realMethod()
implemented
js> proxy.newIPod()
The newIPod method isn't implemented yet. HINT: I accept cash and beer bribes
js>
I was wondering, is there was a way to do something similar for properties? I’d like to write proxy classes that can dispatch on properties as well as methods.
UPDATE: ECMAScript 6 Proxies are widely supported now. Basically, if you don’t need to support IE11, you can use them.
Proxy objects allow you to define custom behavior for fundamental operations, like property lookup, assignment, enumeration, function invocation, etc.
Emulating __noSuchMethod__ with ES6 Proxies
By implementing traps on property access, you can emulate the behavior of the non-standard
__noSuchMethod__trap:Original 2010 answer
There is only one existing thing at the moment that can actually do what you want, but unfortunately is not widely implemented:
There are only two working implementations available at this time, in the latest Firefox 4 betas (it has been around since FF3.7 pre-releases) and in node-proxy for server-side JavaScript –Chrome and Safari are currently working on it-.
It is one of the early proposals for the next version of ECMAScript, it’s an API that allows you to implement virtualized objects (proxies), where you can assign a variety of traps -callbacks- that are executed in different situations, you gain full control on what at this time -in ECMAScript 3/5- only host objects could do.
To build a proxy object, you have to use the
Proxy.createmethod, since you are interested in thesetandgettraps, I leave you a really simple example:Try it out here.
EDIT: The proxy API evolved, the
Proxy.createmethod was removed in favor of using theProxyconstructor, see the above code updated to ES6:The Proxy API is so new that isn’t even documented on the Mozilla Developer Center, but as I said, a working implementation has been included since the Firefox 3.7 pre-releases.
The
Proxyobject is available in the global scope and thecreatemethod can take two arguments, ahandlerobject, which is simply an object that contains properties named as the traps you want to implement, and an optionalprotoargument, that makes you able to specify an object that your proxy inherits from.The traps available are:
The only resource I’ve seen, besides the proposal by itself, is the following tutorial:
Edit: More information is coming out, Brendan Eich recently gave a talk at the JSConf.eu Conference, you can find his slides here: