Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect when a global variable is set in javascript?

In javascript, I can detect when a global variable foo is set (assuming that it is initially undefined) by using Object.defineProperty:

var foo_;
Object.defineProperty(window, 'foo', {
  get: function() {
    return foo_;
  },
  set: function(newFoo) {
    console.log('foo set to ' + newFoo);
    foo_ = newFoo;
  }
});

Is there a more elegant way to do this? One downside is that I cannot call Object.defineProperty on the same property twice. Overriding the entire property just to detect when it is defined seems a bit overkill.

Could I somehow use proxies? I feel like I would have to make a proxy that targets the window object though ... is that efficient?

like image 260
John Hoffman Avatar asked Nov 19 '22 22:11

John Hoffman


1 Answers

Is there a more elegant way to do this?

Not really. Maybe you could (should) hide _foo in a closure instead of creating another global variable.

One downside is that I cannot call Object.defineProperty on the same property twice. Overriding the entire property just to detect when it is defined seems a bit overkill.

The only problem is that you forgot to pass the configurable: true option.

Could I somehow use proxies?

No. You cannot replace the global object with a proxy. The only thing you could do is wrap all the code in a with (new Proxy(…)) { … } block.

like image 197
Bergi Avatar answered Nov 22 '22 16:11

Bergi