gpt4 book ai didi

javascript - 为什么匿名函数表达式和命名函数表达式的初始化如此不同?

转载 作者:数据小太阳 更新时间:2023-10-29 05:55:28 25 4
gpt4 key购买 nike

我正在查看 section 13或 ECMAScript 规范(第 5 版)。匿名函数表达式初始化如下:

Return the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in the LexicalEnvironment of the running execution context as the Scope. Pass in true as the Strict flag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.

此逻辑非常类似于函数声明的初始化方式。但是,请注意命名函数表达式的初始化有何不同。

  1. Let funcEnv be the result of calling NewDeclarativeEnvironment passing the running execution context’s Lexical Environment as the argument
  2. Let envRec be funcEnv’s environment record.
  3. Call the CreateImmutableBinding concrete method of envRec passing the String value of Identifier as the argument.
  4. Let closure be the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in funcEnv as the Scope. Pass in true as the Strict flag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.
  5. Call the InitializeImmutableBinding concrete method of envRec passing the String value of Identifier and closure as the arguments.
  6. Return closure.

我知道命名/匿名函数表达式之间的一大区别是命名函数表达式可以从函数内部递归调用,但我能想到的就是这些。为什么设置如此不同,为什么需要执行这些额外步骤?

最佳答案

所有“跳舞”的原因很简单。

命名函数表达式的标识符需要在函数范围内而不是在函数范围外可用。

typeof f; // undefined

(function f() {
typeof f; // function
})();

如何使 f 在函数中可用?

您不能在外部词法环境中创建绑定(bind),因为 f 不应该在外部可用。而且您不能在内部变量环境中创建绑定(bind),因为……它尚未创建;该函数在实例化时尚未执行,因此 10.4.3(输入函数代码)步骤及其 NewDeclarativeEnvironment 从未发生过。

因此,实现方法是创建一个中间词法环境,它直接从当前词法环境“继承”,然后作为 [[Scope]] 传递到新创建的函数中。

如果我们将 13 中的步骤分解为伪代码,您可以清楚地看到这一点:

// create new binding layer
funcEnv = NewDeclarativeEnvironment(current Lexical Environment)

envRec = funcEnv
// give it function's identifier
envRec.CreateImmutableBinding(Identifier)

// create function with this intermediate binding layer
closure = CreateNewFunction(funcEnv)

// assign newly created function to an identifier within this intermediate binding layer
envRec.InitializeImmutableBinding(Identifier, closure)

所以 f 中的词法环境(例如,在解析标识符时)现在看起来像这样:

(function f(){

[global environment] <- [f: function(){}] <- [Current Variable Environment]

})();

匿名函数看起来像这样:

(function() {

[global environment] <- [Current Variable Environment]

})();

关于javascript - 为什么匿名函数表达式和命名函数表达式的初始化如此不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15129504/

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