如何在JavaScript中检测全局变量何时? [英] How can I detect when a global variable is set in javascript?
问题描述
在javascript中,我可以通过使用 Object.defineProperty 来检测何时设置全局变量
foo
(假设它最初未定义) code>:
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;
}
});
有没有更优雅的方式来做到这一点?一个缺点是我不能在同一个属性两次调用 Object.defineProperty
。覆盖整个属性只是为了检测什么时候被定义似乎有点过分。
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?
不是真的。也许你可以(应该)隐藏 _foo
,而不是创建另一个全局变量。
Not really. Maybe you could (should) hide _foo
in a closure instead of creating another global variable.
一个缺点是我不能在同一个属性两次调用
Object.defineProperty
。覆盖整个属性只是为了检测什么时候被定义似乎有点过分。
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.
唯一的问题是你忘了传递可配置:true
选项。
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.
这篇关于如何在JavaScript中检测全局变量何时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!