Python中的__getattr__在Javascript中

Dmi*_*hin 24 javascript

有没有办法__getattr__在Javascript中模拟Python的方法?

我想拦截Javascript对象属性的'获取'和'集'.

在Python中,我可以编写以下内容:

class A:
    def __getattr__(self, key):
        return key

a = A()
print( a.b )  # Output: b
Run Code Online (Sandbox Code Playgroud)

Javascript怎么样?

Cre*_*esh 9

不可以.最接近的是__defineGetter__在Firefox中可用,它定义了一个函数回调,只要读取指定的属性就会调用它:

navigator.__defineGetter__('userAgent', function(){
    return 'foo' // customized user agent
});

navigator.userAgent; // 'foo'
Run Code Online (Sandbox Code Playgroud)

它的不同之处__getattr__在于它被称为已知属性,而不是作为未知属性的通用查找.

  • 哇!这是令人难以置信的.我希望有一个跨浏览器版本.这将使API编程非常容易. (2认同)