How to using ES6 Arrow function to realize Immediately-Invoked Function Expression (IIFE))? [closed]

主宰稳场 提交于 2019-12-30 07:50:47

问题


How to using ES6 Arrow function to realize IIFEImmediately-Invoked Function Expression?

Here is my demo codes, and it had tested passed!

// ES 6 + IIFE
(() => {
    let b = false;
    console.log(`b === ${b}!`);
    const print = `print()`;
    if(window.print){
        b = true;
        console.log(`b === ${b}!`);
    }
    let x = () => {
        if(b){
            console.log(`Your browser support ${print} method.`);
        }else{
            alert(`Your browser does not support ${print} method.`);
            console.log(`Your browser does not support ${print} method.`);
        };
    }
    x();
})();

const dcs = `IIFE: Douglas Crockford's style`;
// ES 5 + IIFE is OK
(function(){
    alert("IIFE: Douglas Crockford's style");
    console.log(dcs + ", ES 5 is OK!");
}());
// Douglas Crockford's style

// ES 6 + IIFE (error)
/*
    (() => {
        alert(`IIFE: Douglas Crockford's style`);
        console.log(`${dcs},ES 6 is Error!`);
    }());
*/
// Douglas Crockford's style
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=3.0">
</head>
<body>
    <main id="print">
        <section>
            <h1>Javascript ES6 & IIEF</h1>
        </section>
    </main>
</body>
</html>

However, there still has something is wrong about Douglas Crockford's style (IIEF)!

screencut


回答1:


Surround it with parentheses:

(() => console.log('hello'))()


来源:https://stackoverflow.com/questions/40448253/how-to-using-es6-arrow-function-to-realize-immediately-invoked-function-expressi

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