Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept object attribute access in JavaScript [duplicate]

Tags:

javascript

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?

like image 995
huggie Avatar asked Aug 27 '26 09:08

huggie


1 Answers

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.

like image 102
Felix Kling Avatar answered Aug 30 '26 00:08

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!