Why is this grouping operator + function immediately invoked

后端 未结 3 649
自闭症患者
自闭症患者 2020-12-16 18:57

I\'am studying the behaviour of Immediatly Invoked Function Expressions (IIFE) and while doing that I encounterd the following situation.

(function () {
             


        
3条回答
  •  被撕碎了的回忆
    2020-12-16 19:49

    You can write a IIFE also like that: (function () {})()

    By omitting the semicolon, your first codesnippet actually calls the first function with the second IIFE handed over as parameter for the first.

                        executing as parameter for the first IIFE
                                                   \/ 
    (function () {document.write("bar");})( (function () {document.write("foo");}());)
    

    which first prints foo and then bar unlike:

    (function () {
        document.write("bar");
    })();
    
    (function () {
        document.write("foo");
    }());
    

    which prints barfoo or

    (function () {
        document.write("bar");
    });
    
    (function () {
        document.write("foo");
    }());
    

    where the first now is solely considered as grouping operator.

提交回复
热议问题