38

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?

Sample code would be smth like:

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.

  • Adding this as comment as question is closed. For js newbies coming from a python background as I am, what I was looking for was, for `__getattr__`, `myObj[myKey]`, and for `__hasattr__`, `myObj.hasOwnProperty(myKey)`. – Théo Rubenach May 19 '20 at 17:11

2 Answers2

67

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.

user2226755
  • 12,494
  • 5
  • 50
  • 73
Jan Sabbe
  • 671
  • 1
  • 5
  • 3
11

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 []).

Community
  • 1
  • 1
Roatin Marth
  • 23,589
  • 3
  • 51
  • 55
  • thanks. yes, it would be rather __getattr__ –  Oct 20 '09 at 07:32
  • 6
    @Roatin WHY!!!! JS needs this more than any other feature (except the 'less suck' feature that people have been requesting for a decade). – orokusaki Feb 10 '10 at 21:07