Question

Is there a way to implement in javascript the functionality of python's __getattribute__() (or __getattr__())? That is, a method which is called whenever an object is called with method name or property name which cannot be resolved?

For example, a mechanism to implement any of the following:

# 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

I'm most interested in the method syntax, but the property syntax would be a nice bonus. Thanks!

Was it helpful?

Solution

As pointed out by @thg435 the issue was discussed in a narrower scope at Is there an equivalent of the __noSuchMethod__ feature for properties, or a way to implement it in JS? but the answer from there applies here.

An appropriate API for doing this in javascript is in the making, called ECMAScript Harmony Proxies which may have been replaced recently with Direct Proxy. This API is not yet supported cross-platform, but it may work for some platform, such as recent firefox and chrome.

OTHER TIPS

a = { 
  attr1 : 0,
  attr2 : 2
}

// Object {attr1: 0, attr2: 2}

function get(obj, attr) {
  return obj[attr];
}

get(a, 'attr2');

// 2

Another approach is to have the method inside the object:

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

if what you get is function you can call it straight away a.get('myfunc')('myarg') alerts myarg

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top