Immediate function using JavaScript ES6 arrow functions

非 Y 不嫁゛ 提交于 2019-12-28 03:45:11

问题


Does anyone know how to write an immediate function using ES6 arrow syntax?

Here's the ES3/5 way of doing it:

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

I've tried the following but get an unexpected token error on the last line.

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

You can test this here: http://www.es6fiddle.net/hsb8bgu4/


回答1:


From the Arrow functions examples,

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

So, the function invocation operator should be outside.

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

Sample: http://www.es6fiddle.net/hsb8s1sj/




回答2:


Here is my demo codes!

Always remember that 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


来源:https://stackoverflow.com/questions/22138550/immediate-function-using-javascript-es6-arrow-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!