有人知道如何使用ES6箭头语法编写立即函数吗?
下面是ES3/5的方法:
(function () {
//...
}());我尝试了下面的方法,但是在最后一行得到了一个unexpected token错误。
(() => {
//...
}());你可以在这里测试一下:http://www.es6fiddle.net/hsb8bgu4/
发布于 2014-03-03 12:20:16
(() => "foobar")() // returns "foobar" 因此,函数调用操作符应该在外部。
(() => {
//...
})();示例:http://www.es6fiddle.net/hsb8s1sj/
发布于 2016-12-02 18:53:17
这里是我的演示代码!
始终记住
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
发布于 2022-02-07 12:34:50
这里有一个简单的例子。
要定义箭头函数:
const temp = (x)=> {return x+" world";}
// call it as a function
temp("hello") // output: hello world要立即调用箭头函数,请执行以下操作:
const temp = ((x)=> {return x+" world";})("hello")
// use it as a variable:
console.log(temp); // output: hello world
// a self-invoking function without params:
const temp = (()=> {return "world";})()https://stackoverflow.com/questions/22138550
复制相似问题