简体   繁体   English

分配给变量的 IIFE 箭头 function 不起作用

[英]IIFE arrow function assigned to variables is not working

IIFE can be achieved when dealing with function expression.处理function表达式时可以实现IIFE。 One rule is that everything after = sign is an expressien so below code works一个规则是=符号之后的所有内容都是一种表达方式,因此下面的代码有效

const iife = function() { return 5 }(); // iife = 5

Why is that this is not working?为什么这不起作用?

const iife = () => 5() or () => { return 5 }();

Why in case of arrow function I need to use parantheses to make it work?为什么在箭头 function 的情况下我需要使用括号来使其工作?

const iife = (() => 5)() or (() => { return 5 })()

Isn't just () => 5 or () => { return 5 } also an expression? () => 5() => { return 5 }不也是一个表达式吗?

Why is that this is not working?为什么这不起作用?

const iife = () => 5() or () => { return 5 }();

In the former, JS interprets it as you trying to call a function named 5 and return its return value.在前者中,JS 将其解释为您尝试调用名为5的 function 并返回其返回值。

In the latter, JS interprets you trying to call an object as a function { return 5 } and returning its return value.在后者中,JS 将您尝试调用 object 解释为 function { return 5 }并返回其返回值。

Similarly, when calling an IIFE declared with function , curly braces are required.类似地,当调用用 function 声明的function时,需要花括号。 function a() { return 5 }() will not work, but (function a() { return 5 })() will. function a() { return 5 }()将不起作用,但(function a() { return 5 })()将起作用。

It is necessary to wrap the two in brackets so the whole expression is interpreted as a function when called.有必要将两者括在括号中,以便在调用时将整个表达式解释为 function。

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

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