【问题标题】:How to using ES6 Arrow function to realize Immediately-Invoked Function Expression (IIFE))? [closed]如何使用 ES6 箭头函数实现立即调用函数表达式(IIFE)? [关闭]
【发布时间】:2017-03-19 19:08:18
【问题描述】:

如何使用ES6 Arrow函数实现IIFEImmediately-Invoked Function Expression

这是我的演示代码,测试通过了!

// 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) 仍然有问题!

截屏

【问题讨论】:

  • 在你的情况下,你为什么要现在执行它们?
  • 您的问题不清楚。请一位朋友或同事帮助您学习英语。完全不需要完美的英语,但我们确实需要能够理解您的要求。现在,您的问题和您的代码似乎完全不相关。
  • 不确定“数组函数”是什么意思,但现在你的外部函数会立即执行,而不是分配给window.onload,因为最后是()。如果您不希望这样,请删除 ()
  • 如果你指的是() =&gt; {...}而不是function() {...},那么它就是“箭头函数”。
  • 而 IIFE 是 (function(){})()

标签: javascript ecmascript-6 iife arrow-functions self-executing-function


【解决方案1】:

用括号括起来:

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

【讨论】:

  • 感谢您的宝贵时间,看来可行!
猜你喜欢
  • 2016-04-07
  • 2016-12-21
  • 2012-12-28
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 2023-04-04
  • 2017-08-30
相关资源
最近更新 更多