Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's __getattr__ in Javascript [duplicate]

Tags:

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?

like image 667
Dmitry Mukhin Avatar asked Sep 17 '09 19:09

Dmitry Mukhin


People also ask

What is Getattr () used for * What is Getattr () used for to delete an attribute to check if an attribute exists or not to set an attribute?

What is getattr() used for? Explanation: getattr(obj,name) is used to get the attribute of an object. 6.

What does __ Getattr __ do in Python?

__getattr__ Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self ). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.


2 Answers

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)

like image 38
kangax Avatar answered Sep 21 '22 12:09

kangax


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.

like image 167
Crescent Fresh Avatar answered Sep 23 '22 12:09

Crescent Fresh