为什么要记录命名的IIFE而不是具有相同名称的变量? [英] Why is the named IIFE logged instead of the variable with the same name?

查看:40
本文介绍了为什么要记录命名的IIFE而不是具有相同名称的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了某人发布的以下代码.我对它记录的内容感到困惑.它记录功能 a ,而不是 200 .为什么?

  var a = 1;(函数a(){a = 200;console.log(a)})() 

解决方案

因为立即被调用的函数命名为 ,并且该名称不能被重新分配为直接引用其他内容.

任何命名函数表达式也将表现出这种行为.一个函数表达式的函数名为 a ,这意味着直接在函数内部的 a 始终会引用该函数本身,即使您尝试重新分配它.

如果使用严格模式,则可以使错误明确显示:

 'use strict';var a = 1;(函数a(){a = 200;console.log(a)})() 

未捕获的TypeError:分配给常数变量.

具有命名函数表达式有点像具有

 (function a(){const a =< this function> ;;//...})() 

除非尝试重新分配,否则只会在严格模式下抛出.

具体来说,我相信针对此行为的ECMAScript 5规范位于 SetMutableBinding :

  1. 如果envRec中N的绑定是可变绑定,请将其绑定值更改为V.
  2. 否则,这必须是尝试更改不可变绑定的值,因此,如果为true(如果使用S(使用严格模式)),则抛出TypeError异常.

但是直接在函数内部,函数名称绑定是不可变的-请参见

Because the function being immediately invoked is named, and that name cannot be reassigned to refer to something else directly inside the IIFE.

Any named function expressions will exhibit this behavior as well. A function expression whose function is named a will mean that a directly inside the function will always refer to the function itself, even if you try to reassign it.

You can make the error explicit if you use strict mode:

'use strict';
var a = 1;
(function a() {
  a = 200;
  console.log(a)
})()

Uncaught TypeError: Assignment to constant variable.

Having a named function expression is a bit like having

(function a() {
  const a = <this function>;
  // ...
})()

except trying to reassign it will only throw in strict mode.

Specifically, I believe the ECMAScript 5 specification for this behavior is in SetMutableBinding:

  1. If the binding for N in envRec is a mutable binding, change its bound value to V.
  2. Else this must be an attempt to change the value of an immutable binding so if S (strict mode being used) if true throw a TypeError exception.

But directly inside a function, the function name binding is not mutable - see Function Definition:

The production

FunctionExpression : function Identifier ( FormalParameterListopt ) { FunctionBody }

is evaluated as follows:

Call the CreateImmutableBinding concrete method of envRec, passing the String value of Identifier as the argument.

这篇关于为什么要记录命名的IIFE而不是具有相同名称的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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