简体   繁体   English

为什么这个带有箭头功能的 IIFE 不执行?

[英]Why does this IIFE with Arrow function not execute?

I'm curious why this IIFE will run我很好奇为什么这个 IIFE 会运行

(function() {console.log("hi")}());  //"hi"

But with an arrow function it does not run但是使用箭头函数它不会运行

(()=> console.log("hi")());

why is this an error?为什么这是一个错误?

(()=> {return console.log("hi")}());

but moving the parenthase now it works但是现在移动括号可以工作了

(()=> {return console.log("hi")})();//"hi"

The parenthese, and the function keyword are changing the behavior of the IIFE executing, anyone know why?括号和 function 关键字正在改变 IIFE 执行的行为,有人知道为什么吗?

(()=> console.log("hi")());

An IIFE consists of a function definition, immediately followed by () . IIFE 由一个函数定义组成,紧跟在()

An arrow function definition consists of some parameters, followed by => , followed by an expression.箭头函数定义由一些参数组成,后跟=> ,后跟表达式。

console.log(...)() is an expression (meaning call console.log as a function, then call its return value as a function ), so it is treated as part of the function definition (and thus the () do not follow the function definition, because they are part of it). console.log(...)()是一个表达式(意思是将 console.log 作为函数调用,然后将其返回值作为函数调用),因此它被视为函数定义的一部分(因此()做不遵循函数定义,因为它们是函数定义的一部分)。


The parenthese, and the function keyword are changing the behavior of the IFFY executing, anyone know why?括号和 function 关键字正在改变 IFFY 执行的行为,有人知道为什么吗?

They are a grouping operator .它们是分组运算符 They surround the function definition making the () which follow it explicitly outside the function definition.它们包围了函数定义,使得()在函数定义之外显式跟随它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM