JavaScript getter for all properties

Proxy can do it! I’m so happy this exists!! An answer is given here: Is there a javascript equivalent of python’s __getattr__ method? . To rephrase in my own words:

var x = new Proxy({}, {
  get(target, name) {
    return "Its hilarious you think I have " + name
  }
})

console.log(x.hair) // logs: "Its hilarious you think I have hair"

Proxy for the win! Check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

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

Leave a Comment