JavaScript getter for all properties
Asked Answered
G

9

94

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.

Gavin answered 15/6, 2009 at 0:45 Comment(1)
i imagine he's referring to the magic functions __get and __setStephan
S
130

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.

Scincoid answered 20/3, 2016 at 7:35 Comment(6)
It works in Edge too. See caniuse.com for specific browser versions.Thetes
but what if I want to mimic a function call, like myProxy.foo('bar'). I've seen there is apply for functions but is not allowed to use custom names, is always executed on the proxy: myProxy('bar'), we could mimic it with myProxy('foo', 'bar') but then we are missing the magic thingCichlid
@Cichlid If you return a function from the getter, you should absolutely be able to call myProxy.foo('bar').Scincoid
I recognize the answer is correct for the question, but for readers like me who want a default return value, beware that the proxy takes precedence.Enlace
@BarryMcNamara Could you clarify what you mean that the proxy takes precedence?Scincoid
The handler traps calls to the target object. If your target has properties which you want to continue to be gettable, you need to explicitly return them from the handler's get method.Enlace
I
77

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 prop access.

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.

Icebreaker answered 10/4, 2017 at 12:25 Comment(5)
This is the best answer I've found.Abijah
^ this is geniusFig
is not needed to implement "set" inside the proxy for the assignment?Cichlid
@Cichlid No, it works like regular objects, but you can define it.Icebreaker
simply magical!Eu
P
46

The closest you can find is __noSuchMethod__ (__noSuchMethod__ is deprecated), which is JavaScript's equivalent of PHP's __call().

Unfortunately, there's no equivalent of __get/__set, which is a shame, because with them we could have implemented __noSuchMethod__, but I don't yet see a way to implement properties (as in C#) using __noSuchMethod__.

var foo = {
    __noSuchMethod__ : function(id, args) {
        alert(id);
        alert(args);
    }
};

foo.bar(1, 2);
Philanthropist answered 15/6, 2009 at 3:26 Comment(10)
I was actually trying to create a "message eating nil" equivalent, and this does it exactly! Thanks!Gavin
I had no idea about the "message eating nil" concept. ThanksArdith
What about nowjs? They have to be using some sort of __set() and __get() equivalent to make their RPC-style framework actually work. I can't tell how it works from the source code.Grimsley
is there something similar for Chrome/Awesomium? I also found another concept using Harmony Proxies, which unfortunately only works in FF right now.Felecia
@Towa Proxy is the future indeed. It's available on Chrome if you enable experimental JavaScript features under "about:flags". There's no other equivalent for __noSuchMethod__.Ardith
noSuchMethod is non standard and no version of Internet Explorer support it, so it may not work on many of your users' browser.Creative
What about ECMAScript analog of this?Thereabout
IMPORTANT: The link says now: This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.Worn
While noSuchMethod has been dropped, the ECMAScript 2015 (ES6) specification has the Proxy object, with which you can achieve the below (and more).Easel
What is the current status of noSuchMethod ? I cannot find in caniuse, and I think is much better than Proxy, because with proxy we cannot fake a function callCichlid
R
5

Javascript 1.5 does have getter/setter syntactic sugar. It's explained very well by John Resig here

It's not generic enough for web use, but certainly Firefox has them (also Rhino, if you ever want to use it on the server side).

Rugger answered 15/6, 2009 at 2:45 Comment(1)
Not quite __get() and __set(). PHP's version let you monitor ALL properties, even ones that haven't been created yet.Grimsley
R
5

If you really need an implementation that works, you could "cheat" your way arround by testing the second parameter against undefined, this also means you could use get to actually set parameter.

var foo = {
    args: {},

    __noSuchMethod__ : function(id, args) {
        if(args === undefined) {
            return this.args[id] === undefined ? this[id] : this.args[id]
        }

        if(this[id] === undefined) {
            this.args[id] = args;
        } else {
            this[id] = args;
        }
    }
};
Reinert answered 17/10, 2012 at 14:52 Comment(0)
V
1

If you're looking for something like PHP's __get() function, I don't think Javascript provides any such construct.

The best I can think of doing is looping through the object's non-function members and then creating a corresponding "getXYZ()" function for each.

In dodgy pseudo-ish code:

for (o in this) {
    if (this.hasOwnProperty(o)) {
        this['get_' + o] = function() {
            // return this.o -- but you'll need to create a closure to
            // keep the correct reference to "o"
        };
    }
}
Vassili answered 15/6, 2009 at 1:4 Comment(0)
E
0

I ended up using a nickfs' answer to construct my own solution. My solution will automatically create get_{propname} and set_{propname} functions for all properties. It does check if the function already exists before adding them. This allows you to override the default get or set method with our own implementation without the risk of it getting overwritten.

for (o in this) {
        if (this.hasOwnProperty(o)) {
            var creategetter = (typeof this['get_' + o] !== 'function');
            var createsetter = (typeof this['set_' + o] !== 'function');
            (function () {
                var propname = o;
                if (creategetter) {
                    self['get_' + propname] = function () {
                        return self[propname];
                    };
                }
                if (createsetter) {
                    self['set_' + propname] = function (val) {
                        self[propname] = val;
                    };
                }
            })();
        }
    }
Expansile answered 12/11, 2014 at 21:43 Comment(0)
P
0

This is not exactly an answer to the original question, however this and this questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did.

Coming from Python, what I was looking for was an equivalent of obj.__getattr__(key)and obj.__hasattr__(key) methods. What I ended up using is: obj[key] for getattr and obj.hasOwnProperty(key) for hasattr (doc).

Preterhuman answered 19/5, 2020 at 17:23 Comment(0)
A
0

It is possible to get a similar result simply by wrapping the object in a getter function:

const getProp = (key) => {
  const dictionary = {
    firstName: 'John',
    lastName: 'Doe',
    age: 42,
    DEFAULT: 'there is no prop like this'
  }
  return (typeof dictionary[key] === 'undefined' ? dictionary.DEFAULT : dictionary[key]);
}

console.log(getProp('age')) // 42

console.log(getProp('Hello World')) // 'there is no prop like this'
Amygdala answered 7/12, 2021 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.