Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch access to undefined property in JavaScript [duplicate]

The Spider-Monkey JavaScript engine implements the __noSuchMethod__ callback function for JavaScript Objects.

This function is called whenever JavaScript tries to execute an undefined method of an Object.

I would like to set a callback function to an Object that will be called whenever an undefined property in the Object is accessed or assigned to.

I haven't found a __noSuchProperty__ function implemented for JavaScript Objects and I am curios if there is any workaround that will achieve the same result.

Consider the following code:

var a = {};
a.__defineGetter__("bla", function(){alert(1);return 2;});
alert(a.bla);

It is equivalent to [alert(1);alert(2)] - even though a.bla is undefined.

I would like to achieve the same result but to unknown properties (i.e. without knowing in advance that a."bla" will be the property accessed)

like image 832
avri Avatar asked May 03 '10 06:05

avri


3 Answers

Up, guys I think we need to vote for this feature on Google V8 issues list, here http://code.google.com/p/v8/issues/detail?id=264

It seems that there's no much attention to this very important feature :(

like image 25
Alex Craft Avatar answered Nov 08 '22 19:11

Alex Craft


In ECMAScript's next version it should be quite easy, using Object.observe. Read more here: http://addyosmani.com/blog/a-few-new-things-coming-to-javascript/

like image 175
Moshe Avatar answered Nov 08 '22 18:11

Moshe


I would like to set a callback function to an Object that will be called whenever an undefined property in the Object is accessed or assigned to.

While this is not an exhaustive answer, keep in mind that assigning to undefined properties of an object is a key feature of the JavaScript language.

Also note that __noSuchMethod__ is a non-standard method, implemented by Mozilla's JavaScript engines. There is an open feature request for this to be implemented in Google Chrome's V8 engine, but as far as I know this is not supported in other browsers.

As of Feb 2014, It looks like this won't be supported any time soon.

like image 2
Daniel Vassallo Avatar answered Nov 08 '22 19:11

Daniel Vassallo