简体   繁体   English

IIFE 函数是否在调用它的相同函数上下文中执行

[英]Does IIFE function executes in same function context in which it is being called

Just trying to understand how the IIFE functions executes under the hood in JavaScript engine.只是想了解 IIFE 函数是如何在 JavaScript 引擎中执行的。

I know every new function has execution context on call stack, but if IIFE function is called in particular function, then will it create new context for the IIFE, or will that be executed in the same context where it is being called?我知道每个新函数在调用堆栈上都有执行上下文,但是如果在特定函数中调用 IIFE 函数,那么它会为 IIFE 创建新的上下文,还是会在调用它的同一上下文中执行?

function myFunction(){
  console.log('inside the myFunction');
  (function(){
      console.log('inside the IIFE')
  })()
}
myFunction();

So how the execution context is created for normal function and IIFE ?那么如何为普通函数和 IIFE 创建执行上下文呢?

You probably mean "IIFE", or "Immediately Invoked Function Expression".您可能指的是“IIFE”或“立即调用的函数表达式”。

Yes, IIFEs result in their own execution context.是的,IIFE 导致它们自己的执行上下文。 When the IIFE is invoked, it goes onto the call stack, and when the function ends, it gets removed from the call stack, just like with normal named functions.当 IIFE 被调用时,它进入调用堆栈,当函数结束时,它从调用堆栈中删除,就像普通的命名函数一样。 Recursively called IIFEs can result in a stack overflow too, after all:毕竟,递归调用 IIFE 也可能导致堆栈溢出:

 (function iife() { iife() })();

Just like named functions, IIFEs may also even have variables which are defined only inside them, and have their own parameters:就像命名函数一样,IIFE 甚至可能有只在它们内部定义的变量,并有自己的参数:

 (function (param) { const someOtherVarName = true; })('param'); console.log(typeof param, typeof someOtherVarName);

So, in terms of execution context and variable scoping, there isn't really much difference between an IIFE and the invocation of a named function.因此,就执行上下文和变量范围而言,IIFE 和命名函数的调用之间并没有太大区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM