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

时间:2014-03-03 04:12:29

标签: javascript function ecmascript-6 ecmascript-harmony arrow-functions

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

这是ES3 / 5的做法:

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

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

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

您可以在此处测试:http://www.es6fiddle.net/hsb8bgu4/

2 个答案:

答案 0 :(得分:45)

来自Arrow functions examples

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

因此,函数调用运算符应该在外面。

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

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

答案 1 :(得分:5)

以下是我的演示代码!

  

永远记住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!

Immediately-invoked function expression



let x;

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

// ES6 function

// OR

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

// ES6 function




相关问题