Is there a way to catch an attempt to access a non existant property or method?

Well, it seems that with harmony (ES6), there will be a way, and it’s more complicated compared to the way other programing languages do it. Basically, it involves using the Proxy built-in object to create a wrapper on the object, and modify the way default behavior its implemented on it:

obj  = new Proxy({}, 
        { get : function(target, prop) 
            { 
                if(target[prop] === undefined) 
                    return function()  {
                        console.log('an otherwise undefined function!!');
                    };
                else 
                    return target[prop];
            }
        });
obj.f()        ///'an otherwise undefined function!!'
obj.l = function() {console.log(45);};
obj.l();       ///45

The Proxy will forward all methods not handled by handlers into the normal object. So it will be like if it wasn’t there, and from proxy you can modify the target. There are also more handlers, even some to modify the prototype getting, and setters for any property access yes!.

As you would imagine, this isn’t supported in all browsers right now, but in Firefox you can play with the Proxy interface quite easy, just go to the MDN docs

It would make me happier if the managed to add some syntactic sugar on this, but anyway, its nice to have this kind of power in an already powerful language. Have a nice day! 🙂

PD: I didn’t copy rosettacode js entry, I updated it.

Leave a Comment