Basically I need to be able to do this:
var obj = {"foo":"bar"},
arr = [];
with( obj ){
arr.push( foo );
arr.push( notDefinedOnObj ); // fails with 'ReferenceError: notDefinedOnObj is not defined'
}
console.log(arr); // ["bar", ""] <- this is what it should be.
I’m looking for a “global” equivalent of {}.__defineGetter__ or {get} in order to return an empty string for all undefined property getters (note that this is different than a property that is undefined).
You can create a
Proxyto return an empty string whenever undefined properties are accessed.app.js:As question author David Murdoch notes, if you are using node v0.6.18 (the latest stable release at the time this post was written), you must pass the
--harmony_proxiesoption when you run the script:Note that this solution will not work if you use
with, as in:withdoes not seem to call the proxy’sgetmethod when adding the proxy to the scope chain.Note: the proxy handler passed to
Proxy.create()in this is example is incomplete. See Proxy: Common mistakes and misunderstanding for more details.