本文介绍了如何检测新的全局变量的创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我听说过在Javascript中创建新的全局变量,所以无论何时创建全局变量,都会触发事件。 watch()函数,但仅用于查看特定变量名称。我想要一个catchall。

解决方案

我不知道如何使这个工作按需尽快一个变种创建,但我可以建议一个投票方法。在浏览器窗口中,所有全局变成全局窗口对象的成员。 (因为在技术上,窗口是全球对象)。所以你可以做如下的事情:



1)枚举窗口中的所有属性
$ b $

  window.proplist = window.proplist || {}; 
for(propname in window){

if(propname!==proplist){
window.proplist [propname] = true;




$ 2 $)设置一个定时器来定期轮询窗口对于新的属性

  setInterval(onTimer,1000); 



唤醒定时器回调并寻找新的道具

 函数onTimer(){
if(!window.proplist){
return;


(窗口中的propname){

if(!(window.proplist [propname])){
window.proplist [propname ] = true;
onGlobalVarCreated(propname);
}
}
}


I want watch for the creation of new global variables in Javascript so that, anytime a global variable is created, an event is fired.

I've heard of the watch() function but that is only for watching for specific variable names. I want a catchall.

解决方案

I don't know how to make this work "on demand" as soon as a var is created, but I can suggest a polling approach. In a browser window, all global become a member of the global "window" object. (Because technically, "window" is the "global object"). So you could do something like the following:

1) enumerate all the properties on a window

window.proplist = window.proplist || {};
for (propname in window) {

    if (propname !== "proplist") {
      window.proplist[propname] = true;
    }
}

2) Set a timer to periodically "poll" window for new properties

setInterval(onTimer, 1000);

3) Wake up on the timer callback and look for new props

function onTimer() {
        if (!window.proplist) {
            return;
        }

        for (propname in window) {

              if (!(window.proplist[propname])) {
                 window.proplist[propname] = true;
                 onGlobalVarCreated(propname);
              }
        }
}

这篇关于如何检测新的全局变量的创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 04:43