Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

javascript - ES6 immediately invoked arrow function

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');
}()

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

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

Nor this:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');
})()

Is the equivalent of IIFE

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

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'); }();

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.

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.

Regarding the parametrized version, this will work.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...