tags:

views:

109

answers:

1

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.

+3  A: 

Sadly the answer is No. See http://stackoverflow.com/questions/1441005/pythons-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 []).

Roatin Marth
thanks. yes, it would be rather __getattr__
qweasd
@Roatin WHY!!!! JS needs this more than any other feature (except the 'less suck' feature that people have been requesting for a decade).
orokusaki