问题描述
为什么这在Node.js
控制台中(在4.1.1和5.3.0中进行了测试)却不能在浏览器中(在Chrome中进行了测试)而起作用?此代码块应创建并调用记录Ok
的匿名函数.
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)? This code block should create and invoke an anonymous function that logs Ok
.
() => {
console.log('Ok');
}()
此外,虽然上述可以在Node中运行,但这不起作用:
Also, while the above works in Node, this does not work:
n => {
console.log('Ok');
}()
也不是:
(n) => {
console.log('Ok');
}()
奇怪的是,当添加参数时,它实际上在立即调用的部分抛出了SyntaxError
.
What's odd is 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 doesnt 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.
让解析器期望函数表达式的最广泛接受的方法就是将其包装在parens中,因为在JavaScript中,parens不能包含语句.此时,当解析器遇到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立即调用箭头功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!