tags:

views:

352

answers:

2

Is there a way to simulate Python's __getattr__ method in Javascript?

I want to intercept 'gets' and 'sets' of Javascript object's properties.

In Python I can write the following:

class A:
    def __getattr__(self, key):
        return key

a = A()
print( a.b )

What about Javascript?

+2  A: 

No. The closest is __defineGetter__ available in Firefox, which defines a function callback to invoke whenever the specified property is read:

navigator.__defineGetter__('userAgent', function(){
    return 'foo' // customized user agent
});

navigator.userAgent; // 'foo'

It differs from __getattr__ in that it is called for a known property, rather than as a generic lookup for an unknown property.

Crescent Fresh
Wow! That's incredible. I wish there was a cross-browser version of this. It would make API programming so incredibly easy.
orokusaki
+1  A: 

Not in standard ECMAScript-262 3rd ed.

Upcoming 5th edition (currently draft), on the other hand, introduces accessors in object initializers. For example:

var o = {
  a:7,
  get b() { return this.a + 1; },
  set c(x) { this.a = x / 2; }
};

Similar syntax is already supported by Javascript 1.8.1 (as a non-standard extension of course).

Note that there are no "completed" ES5 implementations at the moment (although some are in progress)

kangax