Javascript immediately invoked function patterns

后端 未结 5 385
既然无缘
既然无缘 2020-12-08 05:34

What do you call these patterns? What is the difference between them? When would you use each? Are there any other similar patterns?

(function() {
    con         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 06:09

    Self invoking anonymous function. The function body will be invoked immediately.

    (function() {
        console.log(this);  // window
    })();
    

    Self invoking function. The function body will be invoked immediately. You can still refer to the function x inside the function body. So when you want to execute something immediately, and then you may want to iterate it, you can just reference to it directly.

    (function x() {
        console.log(this);  // window
        console.log(x);     // function x() {}
    })();
    

    The self invoking anonymous function on the right side will be invoked immediately, and the returned value will be assigned to the y. Usually it has a return value when you use this pattern, otherwise, y will be undefined.

    var y = (function() {
        console.log(this);  // window
    })();
    

    IMO, it is same as the third one. The parentheses of the 3rd enclosing the function are just for making the function look like one entire thing. But the functionalities of the both are the same.

    var z = function() {
        console.log(this);  // window
    }();
    

    Similar to the 2nd one, but you can reference the x outside the function scope by using:

    (x = function () {
        console.log(this);  // window
        console.log(x);     // function x() {}
    })();
    console.log(x);         // function x() {}
    

提交回复
热议问题