I want to be able to intercept access attribute to object which previously has not been set in JavaScript. I wonder if it's possible?
The equivalent in Python is the __getattr__ built-in method:
class P(object):
def __getattr__(self, name):
return name
p = P()
x = p.x
p.x doesn't previously exist, but __getattr__ intercept access to a member variable that has not previously been created. Anything similar in JavaScript?
You will be able to do this with Proxies. Example from MDN:
var handler = {
get: function(target, name){
return name in target?
target[name] :
37;
}
};
var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
However, currently browser support is basically non-existent and polyfilling this is not really possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With