是否可以传递立即调用的函数表达式的执行上下文 [英] Is it possible to pass execution context of the immediately invoked function expression

查看:45
本文介绍了是否可以传递立即调用的函数表达式的执行上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

(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的执行上下文。我有权访问函数表达式和对象本身,所以我可以传递或修改一些东西使其工作(不,我不能重写对象或函数内的所有东西)。

I want to have the execution context of IIFE in my global object. I do have access to function expression and object itself so I can pass or modify something to make it work (and no, I can't rewrite everything inside the object or function).

甚至可能吗?

推荐答案

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

The only way I see how that's poosible is by using eval to simulate dynamic scopes. Do this (note that the IIFE must be placed after the global object):

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);
})();

以下是关于如何使用动态范围的参考:是否可以在不使用eval的情况下在JavaScript中实现动态范围?

Here's a reference as on how to use dynamic scopes: Is it possible to achieve dynamic scoping in JavaScript without resorting to eval?

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

I've included an example to demonstrate the power of using dynamic scopes in JavaScript. You can play with the fiddle too.

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);
}());

这篇关于是否可以传递立即调用的函数表达式的执行上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆