Monday, June 3, 2024
110
rated 0 times [  112] [ 2]  / answers: 1 / hits: 72119  / 13 Years ago, tue, october 25, 2011, 12:00:00

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.


More From » metaprogramming

 Answers
12

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 of undefined for a property that doesn't exist:




use strict;
if (typeof Proxy == undefined) {
throw new Error(This browser doesn't support Proxy);
}
let original = {
example: value,
};
let proxy = new Proxy(original, {
get(target, name, receiver) {
if (Reflect.has(target, name)) {
let rv = Reflect.get(target, name, receiver);
if (typeof rv === string) {
rv = rv.toUpperCase();
}
return rv;
}
return missing;
}
});
console.log(`original.example = ${original.example}`); // original.example = value
console.log(`proxy.example = ${proxy.example}`); // proxy.example = VALUE
console.log(`proxy.unknown = ${proxy.unknown}`); // proxy.unknown = missing
original.example = updated;
console.log(`original.example = ${original.example}`); // original.example = updated
console.log(`proxy.example = ${proxy.example}`); // proxy.example = UPDATED




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 get handler function's arguments list:



  • target is the object being proxied (original, in our case).

  • name is (of course) the name of the property being retrieved, which is usually a string but could also be a Symbol.

  • receiver is the object that should be used as this in 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 by Reflect.get.


This lets you create an object with the catch-all getter and setter feature you want:




use strict;
if (typeof Proxy == undefined) {
throw new Error(This browser doesn't support Proxy);
}
let obj = new Proxy({}, {
get(target, name, receiver) {
if (!Reflect.has(target, name)) {
console.log(Getting non-existent property ' + name + ');
return undefined;
}
return Reflect.get(target, name, receiver);
},
set(target, name, value, receiver) {
if (!Reflect.has(target, name)) {
console.log(`Setting non-existent property '${name}', initial value: ${value}`);
}
return Reflect.set(target, name, value, receiver);
}
});

console.log(`[before] obj.example = ${obj.example}`);
obj.example = value;
console.log(`[after] obj.example = ${obj.example}`);




The output of the above is:


Getting non-existent property 'example'
[before] obj.example = undefined
Setting non-existent property 'example', initial value: value
[after] obj.example = value

Note how we get the "non-existent" message when we try to retrieve example when 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 than f = obj.example; and obj.prop("example", value); rather than obj.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:


MyObject.prototype.prop = function(propName) {
if (propName in this) {
// This object or its prototype already has this property,
// return the existing value.
return this[propName];
}

// ...Catch-all, deal with undefined property here...
};

But again, I can't imagine you'd really want to do that, because of how it changes how you use the object.


[#89453] Sunday, October 23, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradford

Total Points: 709
Total Questions: 117
Total Answers: 91

Location: Sao Tome and Principe
Member since Wed, Dec 21, 2022
1 Year ago
;