views:

167

answers:

1

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)

+1  A: 

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.

Daniel Vassallo
Thanks for your answer - I should refine my question as follows:Is there a way to do the same in the Spider-Monkey JavaScript engine?
avri
@avri: `noSuchMethod` is supported in SpiderMonkey, but I doubt that you will find an inbuilt method that catches attempts to assign to undefined properties, because these are actually features of the language.
Daniel Vassallo
I don't think that the fact that assigning to undefined properties of an object being a key feature of the JavaScript language should matter - fact is, JavaScript provides the __defineGetter__ and __defineSetter__ methods.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)
avri
@avri: you may want to edit your question with this example. I think it will provide a better context to what you are looking for.
Daniel Vassallo
Done. Thanks for the advice.
avri