Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magic Methods in JavaScript [duplicate]

Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript.

My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me.

The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for all possible names. I'm not sure if this is possible, but I'd very much like to know.

like image 469
arantius Avatar asked Jun 15 '09 00:06

arantius


2 Answers

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.

like image 122
B T Avatar answered Oct 05 '22 22:10

B T


You can combine proxy and class to have a nice looking code like php:

class Magic {
    constructor () {
        return new Proxy(this, this);
    }
    get (target, prop) {
        return this[prop] || 'MAGIC';
    }
}

this binds to the handler, so you can use this instead of target.

Note: unlike PHP, proxy handles all the property request.

let magic = new Magic();
magic.foo = 'NOT MAGIC';
console.log(magic.foo); // NOT MAGIC
console.log(magic.bar); // MAGIC

You can check which browsers support proxy http://caniuse.com/#feat=proxy.

like image 34
Ali Avatar answered Oct 06 '22 00:10

Ali