6

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?

7
  • I think we can check if it is available in window object like window[foo] Commented Aug 4, 2016 at 5:32
  • I want to detect the moment when the global variable is set and say log something at that time. Commented Aug 4, 2016 at 5:35
  • This feels like an async hack. If it is, don't do it. Use a Promise Commented Aug 4, 2016 at 5:37
  • 1
    If you use it for debugging - why does it matter if you cannot set it twice? If you're using it not for debugging - you better don't. Commented Aug 4, 2016 at 5:47
  • I'm detecting for debugging purposes, but another library has already called Object.defineProperty on that property. Commented Aug 4, 2016 at 5:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

You might also do like

var _bar;
window.__defineGetter__("bar", function(){return this._bar});
window.__defineSetter__("bar", function(v){console.log("bar set to:",v); this._bar = v;});

1 Comment

Don't use deprecated and non-standard builtins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.