是否有与python的__getattr__方法等效的JavaScript? [英] Is there a javascript equivalent of python's __getattr__ method?

查看:39
本文介绍了是否有与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 []).

这篇关于是否有与python的__getattr__方法等效的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆