JavaScript:允许访问您尝试访问的 attr 的 __defineGetter__ 版本?
我一直在寻找 JavaScript 中 Python 的 __getattr__
的替代品,这里的几个答案提到了 Firefox 的 __defineGetter__
。这不仅不跨浏览器兼容,而且实际上不允许您做任何真正有用的事情,就像这个伪代码所做的那样:
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)});
显然这是伪代码,但是有没有任何已知的方法可以在 JavaScript 中真正做到这一点?我知道我可以很好地使用手动版本(最后一行代码),但是当你达到大约 30 个函数时,这会变得非常乏味。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是最漂亮的东西,而且行为也不太一样,但它应该可以工作。你必须这样调用它: api.getAttr('getprofile', 'foo', 'spam');
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');