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?

1
  • 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) Commented May 19, 2020 at 17:12

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! That's incredible. I wish there was a cross-browser version of this. It would make API programming so incredibly easy.
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)

1 Comment

This is not what the original question was asking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.