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?
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.
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