3

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?

huggie
  • 17,587
  • 27
  • 82
  • 139

1 Answers1

2

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks. What's the netiquette in duplicated question here? Should I delete it or leave it as it is? – huggie Jun 15 '15 at 04:00
  • 2
    Leave it. It's like a "guidepost" to the duplicate. – Felix Kling Jun 15 '15 at 04:02
  • 2
    I guess it could be useful. I used with the word "intercept" instead of "catch" or "dynamic setter", so it could be helpful for people who think like I did. – huggie Jun 15 '15 at 06:11