Using 'window', 'document' and 'undefined' as arguments in anonymous function that wraps a jQuery plugin

后端 未结 4 1885
星月不相逢
星月不相逢 2020-12-08 01:06

Honestly, I didn\'t know how to make the title shorter.

I learnt how to write a jQuery plugin by studying the source of SlidesJS plugin. When I encountered something

4条回答
  •  臣服心动
    2020-12-08 01:36

    The inclusion of an identifier in a parameter list is effectively the same as declaring the variable in the function body, e.g.

    function bar(foo) {
    }
    

    is equivalent to

    function bar(foo) {
      var foo;
    }
    

    but of course you just do the first if you want to pass a value to foo.

    The primary reason for doing:

    (function($) {
        // use $ here instead of jQuery
    }(jQuery));
    

    is that when jQuery was released, Prototype.js had already been using "$" as an identifier for its main function for some time. The above pattern allows jQuery and prototype.js to be used in the same page, using "$" as an identifier for different things.

    Passing in document and window is, at best, a micro optimisation that has little benefit. It offers no protection against them being assigned different values than expected. Just don't bother and use window and document inside the function as global identifiers.

    Including undefined in the parameters and not passing it a value is not a sensible way of ensuring undefined really is undefined as it can still be affected if a value is accidentally passed. A safer way is:

    (function() {
        var undefined;
        ...
    }());
    

    Now you are certain that undefined in the scope of the function really is undefined. Or if you want an assignment:

    (function() {
        var undefined = void 0;
        ...
    }());
    

    But that is just extra typing.

提交回复
热议问题