更改闭包变量,供应商JS文件会自动在加载时运行

时间:2015-03-13 04:54:07

标签: javascript closures

所以我相信你以前见过它,一个供应商JS文件修改了全局空间并运行它即将落地的瞬间。我有一个供应商JS文件,它是通过CMS生成的(因此我不能只复制它并在本地使用它),这些文件无法通过CORS访问(所以这里没有.exec)。

此供应商文件在其着陆的瞬间运行并设置其全局变量。我需要运行的一个函数取决于第二个全局变量,它可能正确填充,也可能不正确填充,特别是当多个代码段修改此变量时(全局变量的基本问题)。

无论如何,这里是供应商给我的粗略近似值:

// I have no control over this code:
(function (t) {
    var critter = function (options) {
        // Initialize with options
        return options;
    };

    // I have window that's called "t"
    t.pollution = critter({
        doSomething: function (options) {
            // Do some stuff with options
            alert(t.garbage);
        }
    });
})(window);
// End of my "no control" code...

关键是我有一个全局pollution变量和一个名为doSomething()的函数。我无法修改该代码,但我想使此函数中的t变量不是全局的。

按照正常规范,这应该如何工作如下:

// Sometime later...
(function () {
    // Per the spec, I should modify global variable 'garbage'
    window.garbage = 'wow this is garbage';
    // Lots of potential changes could happen here, not something I would want
    window.pollution.doSomething({});
})();

理想情况下,我想将garbage作为参数发送,但我再也不能乱用该代码。那么有可能在我调用它之前以某种方式将doSomething函数包起来并改变它的t变量吗?

minimal, complete and verifiable example

// I have no control over this code:
(function (t) {
    var critter = function (options) {
        // Initialize with options
        return options;
    };
        
    // I have window that's called "t"
    t.pollution = critter({
        doSomething: function (options) {
            // Do some stuff with options
            alert(t.garbage);
        }
    });
})(window);
// End of my "no control" code...
        
// Sometime later...
(function () {
    // Per the spec, I should modify global variable 'garbage'
    window.garbage = 'wow this is garbage';
    window.pollution.doSomething({});
        
    // I would like to change the "t" in the closure of doSomething();
})();

0 个答案:

没有答案