I’ve been looking for a replacement for Python’s __getattr__ in JavaScript, and a couple answers here mentioned Firefox’s __defineGetter__. Not only is that not cross-browser compatible but it doesn’t really allow for you to do anything really useful like this pseudo-code does:
var api = function()
{
var __getattr__ = function(attr, args)
{
var api_method = attr;
$post(url, api_method, args, function(response){alert(response)});
}
}
// Now api.getprofile('foo', 'spam'); would call the following code behind the scenes:
$post(url, 'getprofile', ['foo', 'spam'], function(response){alert(response)});
Obviously this is pseudo code but is there any known way to do this for real in JavaScript? I understand I could very well use the manual version (the last line of code) but when you get to about 30 functions, this becomes very tedious.
It’s not the prettiest thing and doesn’t act quite the same, but it should work. You’d have to call it like this: api.getAttr(‘getprofile’, ‘foo’, ‘spam’);