Is there a javascript equivalent of python's __getattr__ method?

It's now possible if your browser has support for the ES6 Proxy feature. You can check this in the ECMAScript 6 compatibility table.

If you have the proxy support, you would use it as follows:

let handler = {
  get(target, name) {
    return `Value for attribute ${name}`
  }
}

let x = new Proxy({}, handler);
console.log(x.lskdjoau); // produces message: "Value of attribute 'lskdjoau'"

Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.


Sadly the answer is No. See Python's __getattr__ in Javascript

You've got __defineGetter__, but as you noted you need to know the name of the attribute you will be accessing.

By the way I think you meant __getattr__ (__getitem__ is for things you want to access with []).

Tags:

Javascript