By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,481 Members | 1,211 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,481 IT Pros & Developers. It's quick & easy.

equivalent to python's __getattr__, __setattr__

P: n/a
aum
Hi,

Does Javascript have any equivalent to Python's __getattr__ and
__setattr__ methods?

In other words, the option to define a method of a class that gets invoked
whenever someone tries to fetch an unknown attribute, or set any attribute
of an instance of that class?

I've looked at __defineGetter__, __defineSetter__, __lookupGetter__ and
__lookupSetter__. It did seem like __lookupGetter__ and __lookupSetter__
might have been helpful, but they only seem to return methods that have
already been set with __defineGetter__ and __defineSetter__.

I need a way for an object to invoke a method when any attempt is being
made to fetch an attribute of that object (or, similar to Python, to fetch
an unknown attribute).

Cheers
aum
Oct 9 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a

aum wrote:
Hi,

Does Javascript have any equivalent to Python's __getattr__ and
__setattr__ methods?

In other words, the option to define a method of a class that gets invoked
whenever someone tries to fetch an unknown attribute, or set any attribute
of an instance of that class?
No. There is a relevant thread here:

<URL:
http://groups.google.com/group/comp....14aac6a0a90557
>
The most relevant response was from petermichaux:

<quote>
I think you want to use a setter method to encapsulate the change and
whatever else needs to happen. So for a class you write yourself.

Foo.prototype.setDescription = function(val) {
if (this.validate(val)) {
this.description = val;
// now do other stuff here.
}

};

Perhaps you have to wrap the browser provided objects in your own class
so that you can then have a setter method. :
</quote>
--
Rob

Oct 9 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.