self executing function jquery vs javascript difference

后端 未结 9 829
长发绾君心
长发绾君心 2020-12-02 19:59

What are the difference among -

First :-

(function () {

    var Book = \'hello\';

}());

Second:-

9条回答
  •  余生分开走
    2020-12-02 20:38

    As the other answers pointed out they are all self executing anonymous function or immediate anonymous functions.

    The third example is use to create aliases for variables outside the function. This is a good way to prevent name conflicts and creating code where it's possible to easily change a module used in the function. It's essentially a form of dependency injection.

    (function (doc, win, $, myModule) {
        // Code
    }(document, window, jQuery, window.MYAPP.myModule));
    

    doc, win, $ and myModule are injected variables. With this pattern it's trivial to change any of the injected components. Like this

    (function (doc, win, $, myModule) {
        // Code
    }(document, window, jQuery, window.MYAPP.myModule2)); //Use myModule2 instead myModule
    

提交回复
热议问题