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

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

问题描述

这是一个名为 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.

推荐答案

我相信这块 ecma 规范 解释了这种行为.这特别涉及命名函数表达式

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. 让闭包作为创建一个新的 Function 对象的结果,如 13.2 中指定的那样,参数由 FormalParameterListopt 指定,主体由 FunctionBody 指定.传入 funcEnv 作为作用域.如果 FunctionExpression 包含在严格代码中或其 FunctionBody 是严格代码,则将 true 作为 Strict 标志传递.
  5. 调用 envRec 的 InitializeImmutableBinding 具体方法,传入 Identifier 的 String 值和闭包作为参数.
  6. 返回关闭.

在创建命名函数表达式的范围时使用 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天全站免登陆