I am aware of how to create getters and setters for properties whose names one already knows, by doing something like this:
// A trivial example:
function MyObject(val){
this.count = 0;
this.value = val;
}
MyObject.prototype = {
get value(){
return this.count < 2 ? "Go away" : this._value;
},
set value(val){
this._value = val + (++this.count);
}
};
var a = new MyObject('foo');
alert(a.value); // --> "Go away"
a.value = 'bar';
alert(a.value); // --> "bar2"
Now, my question is, is it possible to define sort of catch-all getters and setters like these? I.e., create getters and setters for any property name which isn’t already defined.
The concept is possible in PHP using the __get() and __set() magic methods (see the PHP documentation for information on these), so I’m really asking is there a JavaScript equivalent to these?
Needless to say, I’d ideally like a solution that is cross-browser compatible.
This changed as of the ES2015 (aka "ES6") specification: JavaScript now has proxies. Proxies let you create objects that are true proxies for (facades on) other objects. Here’s a simple example that turns any property values that are strings to all caps on retrieval, and returns
"missing"instead ofundefinedfor a property that doesn’t exist:Operations you don’t override have their default behavior. In the above, all we override is
get, but there’s a whole list of operations you can hook into.In the
gethandler function’s arguments list:targetis the object being proxied (original, in our case).nameis (of course) the name of the property being retrieved, which is usually a string but could also be a Symbol.receiveris the object that should be used asthisin the getter function if the property is an accessor rather than a data property. In the normal case this is the proxy or something that inherits from it, but it can be anything since the trap may be triggered byReflect.get.This lets you create an object with the catch-all getter and setter feature you want:
The output of the above is:
Note how we get the "non-existent" message when we try to retrieve
examplewhen it doesn’t yet exist, and again when we create it, but not after that.Answer from 2011 (obsoleted by the above, still relevant to environments limited to ES5 features like Internet Explorer):
No, JavaScript doesn’t have a catch-all property feature. The accessor syntax you’re using is covered in Section 11.1.5 of the spec, and doesn’t offer any wildcard or something like that.
You could, of course, implement a function to do it, but I’m guessing you probably don’t want to use
f = obj.prop("example");rather thanf = obj.example;andobj.prop("example", value);rather thanobj.example = value;(which would be necessary for the function to handle unknown properties).FWIW, the getter function (I didn’t bother with setter logic) would look something like this:
But again, I can’t imagine you’d really want to do that, because of how it changes how you use the object.