ES6 立即调用箭头函数 [英] ES6 immediately invoked arrow function

查看:56
本文介绍了ES6 立即调用箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这在 Node.js 控制台中有效(在 4.1.1 和 5.3.0 中测试),但在浏览器中不起作用(在 Chrome 中测试)?

Why does this work in a Node.js console (tested in 4.1.1 and 5.3.0), but doesn't work in the browser (tested in Chrome)?

此代码块应创建并调用一个匿名函数,该函数记录 Ok.

This code block should create and invoke an anonymous function that logs Ok.

() => {
  console.log('Ok');
}()

此外,虽然上述在 Node.js 中有效,但这不起作用:

Also, while the above works in Node.js, this does not work:

n => {
  console.log('Ok');
}()

也不是这个:

(n) => {
  console.log('Ok');
}()

奇怪的是,当添加参数时,它实际上在立即调用部分抛出了一个SyntaxError.

It is odd that when the parameter is added, it actually throws a SyntaxError at the immediately-invoking part.

推荐答案

你需要把它变成一个函数表达式,而不是一个不需要名字的函数定义并使其成为有效的 JavaScript.

You need to make it a function expression instead of function definition which doesn't need a name and makes it a valid JavaScript.

(() => {
  console.log('Ok');
})()

相当于 IIFE

(function(){
   console.log('Ok')
})();

这在 Node.js 中有效但在 Chrome 中无效的可能原因是它的解析器将其解释为自执行函数,如下

And the possible reason why this works in Node.js but not in Chrome is because its parser interprets it as a self executing function, as this

function() { console.log('hello'); }();

Node.js 中运行良好.这是一个函数表达式,Chrome 和 Firefox 以及大多数浏览器都是这样解释的.您需要手动调用它.

works fine in Node.js. This is a function expression, and Chrome and Firefox and most of the browser interprets it this way. You need to invoke it manually.

告诉解析器期待一个函数表达式的最广为接受的方式就是将它包装在括号中,因为在 JavaScript 中,括号不能包含语句.此时,当解析器遇到 function 关键字时,它知道将其解析为函数表达式而不是函数声明.

The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

关于参数化版本,这会起作用.

((n) => {
  console.log('Ok');
})()

这篇关于ES6 立即调用箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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