【问题标题】:javascript: implement something like python's __getattribute__?javascript:实现类似于 python 的 __getattribute__ 的东西?
【发布时间】:2013-05-08 14:31:38
【问题描述】:

有没有办法在 javascript 中实现 python 的 __getattribute__()(或 __getattr__())的功能?也就是当一个对象被调用时调用的方法名或属性名无法解析?

例如,实现以下任一功能的机制:

# Python's method syntax 
o.Name(args) # o.__getattr__('Name') is called and returns 
             # a function which is called with args
# Alternative method syntax
o.Name(args) # o.__getattr__('Name', args) is called and returns a value

# Properties syntax
o.Name = v  # o.__getattr__('Name', v) is called
v = o.Name  # o.__getattr__('Name') is called and returns a value

我对方法语法最感兴趣,但属性语法将是一个不错的奖励。谢谢!

【问题讨论】:

标签: javascript python dynamic duck-typing


【解决方案1】:

正如@thg435 所指出的,该问题在Is there an equivalent of the __noSuchMethod__ feature for properties, or a way to implement it in JS? 的讨论范围较窄,但此处的答案适用于此。

在 javascript 中执行此操作的适当 API 正在制作中,称为 ECMAScript Harmony Proxies,最近可能已被 Direct Proxy 替换。此 API 尚不支持跨平台,但它可能适用于某些平台,例如最近的 firefox 和 chrome。

【讨论】:

    【解决方案2】:
    a = { 
      attr1 : 0,
      attr2 : 2
    }
    
    // Object {attr1: 0, attr2: 2}
    
    function get(obj, attr) {
      return obj[attr];
    }
    
    get(a, 'attr2');
    
    // 2
    

    另一种方法是将方法放在对象内部:

    a = { 
      attr1 : 0,
      attr2 : 2,
      myfunc: function(args) {
        alert(args);
      },
      get   : function(attr) {
        return this[attr];
      }
    }
    
    // Object {attr1: 0, attr2: 2, get: function}
    
    a.get('attr2');
    
    // 2
    

    如果你得到的是函数,你可以直接调用它a.get('myfunc')('myarg')alertsmyarg

    【讨论】:

    • 我希望有一种更“自动”的方法,适用于“a.attr3”...
    • @UriCohen 当然你可以通过a.attr2获取一个属性值,如果它是一个函数你可以调用它a.myfunc()
    猜你喜欢
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多