gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:49:48 24 4
gpt4 key购买 nike

考虑以下代码:

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

有可能吗?

最佳答案

我认为这是可行的唯一方法是使用 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);
}());

关于javascript - 是否可以传递立即调用的函数表达式的执行上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10279026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com