26

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 )  # Output: b

What about Javascript?

Johannes Sasongko
  • 4,178
  • 23
  • 34
Dmitry Mukhin
  • 6,649
  • 3
  • 29
  • 31
  • Adding this as comment as question is closed. For js newbies coming from a python background as I am, what I was looking for was, for __getattr__, myObj[myKey], and for __hasattr__, myObj.hasOwnProperty(myKey) – Théo Rubenach May 19 '20 at 17:12

2 Answers2

8

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
  • 115,249
  • 25
  • 154
  • 140
  • 2
    Wow! That's incredible. I wish there was a cross-browser version of this. It would make API programming so incredibly easy. – orokusaki Feb 10 '10 at 20:50
0

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)

Community
  • 1
  • 1
kangax
  • 38,898
  • 13
  • 99
  • 135