有谁知道如何使用ES6箭头语法编写立即函数?
这是ES3 / 5的做法:
(function () {
//...
}());
我尝试过以下操作但最后一行出现unexpected token
错误。
(() => {
//...
}());
您可以在此处测试:http://www.es6fiddle.net/hsb8bgu4/
答案 0 :(得分:45)
(() => "foobar")() // returns "foobar"
因此,函数调用运算符应该在外面。
(() => {
//...
})();
答案 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!`);
})();

Immediately-invoked function expression
let x;
(x = () => {
console.log(`ES6 ${typeof(x)}`);
})();
// ES6 function
// OR
(() => {
console.log(`ES6 ${typeof(Symbol)}`);
})();
// ES6 function