Proxy:
let YOUR_OBJECT = {
key1: 111,
};
/***/
YOUR_OBJECT = new Proxy(YOUR_OBJECT, {
get(obj_origin, key, obj_proxy) {
if (!(key in obj_origin)) {
// console.error(key + ' not found!');
// throw new Error(key + ' not found!');
return key;
}
return Reflect.get(...arguments);
},
});
/***/
console.log(YOUR_OBJECT.key1); // 111
console.log(YOUR_OBJECT.key2); // "key2"
This is useful mainly for testing reasons, when you have a big/old code and don't even know, which keys may be required.
If you're coding from scratch, usage of proxy may be sign of bad design (it's doing work behind the scene, that may be not clear for reader or future you), better to use (as option) direct functions .get(key), .set(key, val)
const obj = {
_storage: {
key1: 111,
},
get: function(key) {
if (!(key in this._storage)) {
return key;
}
return this._storage[key];
},
set: function(key, val) {
this._storage[key] = val;
},
};
/***/
console.log(obj.get('key1')); // 111
console.log(obj.get('key2')); // "key2"
You are typing a bit more, but saving much time for future, when you will try to figure out, what's going on.