Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...