使用 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
Immediate function using JavaScript ES6 arrow 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 token
error 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.
所以,函数调用操作符应该在外面。
(() => {
//...
})();
回答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!`);
})();
Immediately-invoked function expression
let x;
(x = () => {
console.log(`ES6 ${typeof(x)}`);
})();
// ES6 function
// OR
(() => {
console.log(`ES6 ${typeof(Symbol)}`);
})();
// ES6 function