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?
What is getattr() used for? Explanation: getattr(obj,name) is used to get the attribute of an object. 6.
__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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With