是否有与python的__getattr__方法等效的JavaScript?
在python中,您可以定义一个具有 __ getattr __(self,key)
方法的对象,以处理所有未知属性以编程方式可解决,但是在javascript中,您只能为pre-定义getter和setter定义的属性.是否有通用的方法也可以在javascript中完成前一件事情?
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?
示例代码如下:
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.
遗憾的是,答案是否定的.请参见Python的__getattr__用Javascript
Sadly the answer is No. See Python's __getattr__ in Javascript
您已经 __ defineGetter __
,但正如您指出的那样,您需要知道将要访问的属性的名称.
You've got __defineGetter__
, but as you noted you need to know the name of the attribute you will be accessing.
按照我认为您的意思, __ getattr __
( __ getitem __
是要使用 []
访问的内容).
By the way I think you meant __getattr__
(__getitem__
is for things you want to access with []
).