In javascript, I can determine when a global variable is set foo(assuming it was originally undefined) 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 drawback is that I cannot call Object.definePropertythe same property twice . Overriding an entire property just to determine when it is defined seems a bit overkill.
Can I use proxies somehow ? I feel like I need to make a proxy that targets the window object, though ... is this effective?
source
share