为什么不能给具有相同名称的命名函数表达式中的变量赋值? [英] Why can’t I assign values to a variable inside a named function expression with the same name?

查看:167
本文介绍了为什么不能给具有相同名称的命名函数表达式中的变量赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个名为test的命名函数表达式.在内部,我将123分配给一个变量,也称为test.然后记录test.该函数在控制台中打印其主体,但不打印123.发生这种行为的原因是什么?

This is a named function expression with the name test. Inside, I assign 123 to a variable, also named test. Then test is logged. The function prints its body in the console, but not 123. What is the reason for such behavior?

(function test() {
  test = 123;
  console.log( test );
}());

我对函数执行的解释在哪里失败?

Where does my explanation of function execution fail?

  1. 开始执行函数:test是引用函数本身的局部变量
  2. 将局部变量test重新分配给数字123
  3. console.log(test)显示数字123.
  1. Start of function execution: test is a local variable that references the function itself
  2. Local variable test is reassigned to number 123
  3. console.log(test) shows the number 123.

推荐答案

我相信

I believe this piece of the ecma spec explains this behavior. This relates specifically to named Function Expressions

生产

FunctionExpression:函数标识符(FormalParameterListopt){FunctionBody}

评估如下:

  1. 让funcEnv成为调用NewDeclarativeEnvironment的结果,并传递运行中的执行上下文的词法环境作为参数
  2. 让envRec成为funcEnv的环境记录.
  3. 调用envRec的CreateImmutableBinding具体方法,将Identifier的String值作为参数传递.
  4. 闭包是使用FormalParameterListopt指定的参数和FunctionBody指定的主体创建13.2中指定的新Function对象的结果.传递funcEnv作为作用域.如果FunctionExpression包含在严格代码中,或者其FunctionBody是严格代码,则将Strict标志作为true传递.
  5. 调用envRec的InitializeImmutableBinding具体方法,将Identifier和Closure的String值作为参数传递.
  6. 关闭封包.
  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.

在创建命名函数表达式的作用域时使用CreateImmutableBinding会将标识符(在本例中为test)创建为不可变变量.这就是为什么对其赋值不会更改其值的原因.

The use of CreateImmutableBinding when creating the scope of a named Function Expression, creates the identifier (in this case test) as an immutable variable. That is why assignment to it does not change its value.

这篇关于为什么不能给具有相同名称的命名函数表达式中的变量赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆