使用JavaScript ES6箭头功能的即时功能

d13*_*d13 35 javascript function ecmascript-harmony ecmascript-6 arrow-functions

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

这是ES3/5的做法:

(function () {
   //...
}());
Run Code Online (Sandbox Code Playgroud)

我尝试了以下但unexpected token在最后一行得到错误.

(() => {
  //...
}());
Run Code Online (Sandbox Code Playgroud)

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

the*_*eye 48

从Arrow函数示例中,

(() => "foobar")() // returns "foobar" 
Run Code Online (Sandbox Code Playgroud)

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

(() => {
  //...
})();
Run Code Online (Sandbox Code Playgroud)

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

  • 这种方式也适用于常规函数,无论如何它更有意义 - 包装函数本身使其成为表达式,然后调用该表达式.当你包装整个函数调用它也有效的事实是一个奇怪的怪癖imo,我很高兴这不适用于箭头 (2认同)

xgq*_*rms 7

这是我的演示代码!

永远记住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!`);
})();
Run Code Online (Sandbox Code Playgroud)

使用ES6箭头功能可实现IIEF!

立即调用的函数表达式

let x;

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

// ES6 function

// OR

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

// ES6 function
Run Code Online (Sandbox Code Playgroud)