如何使用ES6 Arrow函数来实现立即调用函数表达式(IIFE)? [英] How to using ES6 Arrow function to realize Immediately-Invoked Function Expression (IIFE))?

查看:101
本文介绍了如何使用ES6 Arrow函数来实现立即调用函数表达式(IIFE)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ES6 Arrow函数实现IIFE 立即调用的函数表达式?

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>

但是,道格拉斯·克罗克福德(Douglas Crockford)的风格(IIEF)仍然有问题!

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

屏幕截图

推荐答案

用括号括起来:

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

这篇关于如何使用ES6 Arrow函数来实现立即调用函数表达式(IIFE)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆