使用 JavaScript ES6 箭头函数的立即函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22138550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:31:55  来源:igfitidea点击:

Immediate function using JavaScript ES6 arrow functions

javascriptfunctionecmascript-6ecmascript-harmonyarrow-functions

提问by d13

Does anyone know how to write an immediate function using ES6 arrow syntax?

有谁知道如何使用 ES6 箭头语法编写立即函数?

Here's the ES3/5 way of doing it:

这是 ES3/5 的做法:

(function () {
   //...
}());

I've tried the following but get an unexpected tokenerror on the last line.

我尝试了以下操作,但unexpected token在最后一行出现错误。

(() => {
  //...
}());

You can test this here: http://www.es6fiddle.net/hsb8bgu4/

你可以在这里测试:http: //www.es6fiddle.net/hsb8bgu4/

回答by thefourtheye

From the Arrow functions examples,

箭头函数示例中

(() => "foobar")() // returns "foobar" 

So, the function invocation operator should be outside.

所以,函数调用操作符应该在外面。

(() => {
  //...
})();

Sample: http://www.es6fiddle.net/hsb8s1sj/

示例:http: //www.es6fiddle.net/hsb8s1sj/

回答by xgqfrms

Here is my demo codes!

这是我的演示代码!

Always remember that function_name+()=== function_caller

永远记住function_name+ ()=== function_caller

/* ES5 */

// normal function

function abc(){
    console.log(`Hello, ES5's function!`);
}
abc();

var abc = function xyz(){
    console.log(`Hello, ES5's function!`);
};
abc();

// named function

var abc = function xyz(){
    console.log(`Hello, ES5's function!`);
}();


// anonymous function
// 1
(function(){
    console.log(`Hello, ES5's IIFE!`);
})();

// 2
(function(){
    console.log(`Hello, ES5's IIFE!`);
}());

// 3

var abc = function(){
    console.log(`Hello, ES5's function!`);
}();


/* ES6 */

// named arrow function
const xyz = () => {
    console.log(`Hello, ES6's Arrow Function!`);
};
xyz();


const xyz = (() => {
    console.log(`Hello, ES6's Arrow Function!`);
})();


// Uncaught SyntaxError: Unexpected token (

/*
const xyz = (() => {
    console.log(`Hello, ES6's Arrow Function!`);
}());
*/

// anonymous arrow function
(() => {
    console.log(`Hello, ES6's Arrow Function!`);
})();

Using ES6 Arrow Functions realize IIEF!

使用 ES6 箭头函数实现 IIEF!

Immediately-invoked function expression

立即调用函数表达式

let x;

(x = () => {
  console.log(`ES6 ${typeof(x)}`);
})();

// ES6 function

// OR

(() => {
  console.log(`ES6 ${typeof(Symbol)}`);
})();

// ES6 function