gpt4 book ai didi

javascript - javascript匿名函数的生命周期是多少?

转载 作者:可可西里 更新时间:2023-11-01 01:23:06 26 4
gpt4 key购买 nike

如果我在全局范围内写这个:

(function(){})();

匿名函数是在语句执行时创建,语句执行后立即销毁吗?

如果我把它写在一个函数中:

function foo()
{
var a=1;
(function(){})();
a++;
}

匿名函数是在 foo 返回之前存在,还是只在该语句执行期间存在?

最佳答案

在这种特殊情况下,大多数引擎会完全优化该功能,因为它什么都不做。

但是让我们假设函数包含代码并且确实被执行了。在这种情况下,该函数将一直存在,作为编译代码、字节码或解释器的 AST。

不会一直存在的部分是作用域和可能创建的闭包。为该函数和闭包创建的作用域仅在执行该函数或存在对具有特定绑定(bind)作用域/闭包的函数的引用时才存在。

所以组合函数引用+作用域将在语句(function(){})();执行时分配,并可以在执行后释放那句话。但 function(){} 的编译版本可能仍存在于内存中供以后使用。

对于即时编译和优化的引擎,一个函数甚至可能存在于不同的编译版本中。

现代 js 引擎的 JIT+优化器部分是一个复杂的话题,可以在这里找到 v8 的粗略描述 html5rocks: JavaScript Compilation :

In V8, the Full compiler runs on all code, and starts executing code as soon as possible, quickly generating good but not great code. This compiler assumes almost nothing about types at compilation time - it expects that types of variables can and will change at runtime.

In parallel with the full compiler, V8 re-compiles "hot" functions (that is, functions that are run many times) with an optimizing compiler. [...] In the optimizing compiler, operations get speculatively inlined (directly placed where they are called). This speeds execution (at the cost of memory footprint), but also enables other optimizations.

因此,生成的代码可能与原始代码几乎没有任何相似之处。

因此,立即调用的函数表达式甚至可以使用内联完全优化掉。

关于javascript - javascript匿名函数的生命周期是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52812131/

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