gpt4 book ai didi

javascript - 为什么定义在 'if'条件表达式部分的函数在外面不可见?

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

if (function f() {}) {
console.log(f) // Throw an error: f is not defined
}

为什么日志会报错,f没有在上面的表达式中定义?


你会认为这等同于:

function f () {}
if (true) {
console.log(f); // Throw an error: f is not defined
}

最佳答案

当你说

function f () {}

是一个函数声明语句。该函数将在封闭环境中定义。因此,如果它是在另一个函数中定义的,那么该函数将在该环境中定义,您可以在其中通过名称访问该函数。

但是,当您在表达式中使用函数声明时,它不会被视为函数声明,而是函数表达式,并且会像这样计算(引用自 ECMA Script 5.1 Standard Specification )

13 Function Definition: Semantics

The production

FunctionExpression :

 function Identifier ( FormalParameterListopt ) { FunctionBody }

is evaluated as follows:

  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(N) 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(N, V) concrete method of envRec passing the String value of Identifier and closure as the arguments.
  6. Return closure.

因此,当您在表达式中创建函数时,

  1. 将创建一个新的环境上下文(见第一项)

  2. 函数的名称将绑定(bind)到新创建的环境(见第三项)。

  3. 函数体将用于创建实际的函数对象(见第四项)

  4. 创建的实际函数对象绑定(bind)到新创建的上下文中的函数名称(参见第五项)

  5. 然后返回函数对象。

由程序将函数对象分配给当前环境上下文中的变量以保留函数。否则,当表达式计算完成时,新创建的环境上下文将变得无效。因此,函数 f 将在外部不可见。

关于javascript - 为什么定义在 'if'条件表达式部分的函数在外面不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763949/

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