函数体和函数本身的变量具有相同的名称(JavaScript) [英] Variable in function body and function itself have the same name (JavaScript)

查看:79
本文介绍了函数体和函数本身的变量具有相同的名称(JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

此功能在控制台中打印它的主体,但不是'123'。这种行为的原因是什么?

This function prints it's body in console, but not '123'. What is the reason of such behavior?

我对函数执行的解释失败了吗?

Where my explanation of function execution fails?


  1. 开始执行功能; 'test'是一个引用函数本身的局部变量;

  2. 局部变量'test'被重新赋值为123;

  3. console.log变量'test',这是一个数字。


推荐答案

我相信这一段< a href =http://www.ecma-international.org/ecma-262/5.1/#sec-13> ecma规范解释了这种行为。这与命名函数表达式具体相关

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


生产

The production

FunctionExpression:function Identifier(FormalParameterListopt){FunctionBody}

评估如下:


  1. 让funcEnv成为调用NewDeclarativeEnvironment传递正在运行的执行上下文的词法环境作为参数的结果

  2. 让envRec成为funcEnv的环境记录。

  3. 调用envRec的CreateImmutableBinding具体方法,将Identifier的String值作为参数传递。

  4. 让闭包成为结果使用FormalParameterListopt指定的参数和FunctionBody指定的主体创建13.2中指定的新Function对象。传入funcEnv作为范围。如果FunctionExpression包含在严格代码中或者其FunctionBody是严格代码,则传入true作为Strict标志。

  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.

这篇关于函数体和函数本身的变量具有相同的名称(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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