是否可以传递立即调用的函数表达式的执行上下文

时间:2012-04-23 10:42:28

标签: javascript

请考虑以下代码:

(function() {
    var a = 5;
    var someFunc = function() { ... };
    function anotherFunc() {
        ...
    };
})();

window.myGlobalObj = {
    init: function() {
        // and somehow here I want to  access to the IIFE context
    }
};

我想在我的全局对象中拥有IIFE的执行上下文。我可以访问函数表达式和对象本身,所以我可以传递或修改某些东西使它工作(不,我不能重写对象或函数内的所有东西)。

甚至可能吗?

3 个答案:

答案 0 :(得分:2)

您的IIFE的“内容”,即asomeFunc等,是该功能范围的本地,因此您只能在该范围内访问它们。但是你可以在IIFE中分配window.myGlobalObj

(function() {
    var a = 5;
    var someFunc = function() { ... };
    function anotherFunc() {
        ...
    };

    window.myGlobalObj = {
        init: function() {
           // and somehow here I want to  access to the IIFE context
        }
    };

})();

然后init函数可以访问这些变量,因为它们在其包含的范围内。

编辑:如果你不能将myGlobalObj的定义移到IIFE,我唯一能想到的就是使用IIFE来创建你从myGlobalObj访问的第二个全局对象:

(function() {
    var a = 5;
    var someFunc = function() { ... };
    function anotherFunc() {
        ...
    };

    // create a global object that reveals only the parts that you want
    // to be public
    window.mySecondObject = {
       someFunc : someFunc,
       anotherFunc : anotherFunc
    };
})();

window.myGlobalObj = {
    init: function() {
        window.mySecondObject.someFunc();
    }
};

答案 1 :(得分:2)

通过使用eval来模拟动态范围,我唯一能看出这是多么可能。这样做(注意IIFE必须放在全局对象之后):

window.myGlobalObj = {
    init: function() {
        // and somehow here I want to  access to the IIFE context
    }
};

(function() {
    var a = 5;
    var someFunc = function() { ... };
    function anotherFunc() {
        ...
    };

    eval("(" + String(window.myGlobalObj.init) + ")").call(window.myGlobalObj);
})();

以下是有关如何使用动态范围的参考:Is it possible to achieve dynamic scoping in JavaScript without resorting to eval?

编辑我已经提供了一个示例来演示在JavaScript中使用动态范围的强大功能。您也可以使用fiddle

var o = {
    init: function () {
        alert(a + b === this.x); // alerts true
    },
    x: 5
};

(function () {
    var a = 2;
    var b = 3;

    eval("(" + String(o.init) + ")").call(o);
}());

答案 2 :(得分:0)

没有。这不可能。您要访问的上下文称为closure,只能在函数内部访问(在您的情况下,匿名函数(IIFE,您如何调用它))。有关闭包的更多信息,请遵循优秀的Douglas Crockfords The Javascript programming language video tutorial

您必须将这些属性放在某个共享对象上。