Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  191] [ 7]  / answers: 1 / hits: 16825  / 15 Years ago, wed, october 7, 2009, 12:00:00

In python you can define a object having __getattr__(self,key) method to handle all unknown attributes to be solvable in programmatic manner, but in javascript you can only define getters and setters for pre-defined attributes. Is there a generic way of getting the former thing done also in javascript?



Sample code would be smth like:



function X() {};
X.prototype={
__getattr__:function(attrname) {
return Value for attribute '+attrname+';
}
}

x=new X()
alert(x.lskdjoau); // produces message: Value of attribute 'lskdjoau'


Key point is getting value of attribute programmatically depending on the name of the attribute. Pre-setting attribute does not help because during init there is no information what attributes might be requested.


More From » javascript

 Answers
113

Sadly the answer is No. See Python's __getattr__ in Javascript



You've got __defineGetter__, but as you noted you need to know the name of the attribute you will be accessing.



By the way I think you meant __getattr__ (__getitem__ is for things you want to access with []).


[#98563] Wednesday, September 30, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;