内联函数调用有什么好处?

Alv*_*ong 12 javascript jquery

我看到了这段代码(显然它是在jQuery中,有修改)

(function(window,undefined){
    var jQuery=(function(){
        var jQuery=something;
        jQuery.xxx=xxx;
        //...
        return jQuery;
    })();
    //...
    window.jQuery=window.$=jQuery;
})(window);
Run Code Online (Sandbox Code Playgroud)

虽然我理解在内联函数调用中包装代码可以清楚地定义变量范围,但我不明白它的好处

  1. window使用参数传递而不是直接使用它,
  2. undefined通过未定义的参数获取实例,以及
  3. jQuery通过另一个内联函数调用的返回值定义.有人可以解释一下吗?

编辑更清楚地写#3:

我理解的是代码jQuery在另一个函数内定义然后返回它.

//(function(window,undefined){
var jQuery=(function(){
    // Inside this function defines jQuery and return it?
    var jQuery=function(selector,context){
        return new jQuery(selector,context); //simplified
    };
    jQuery.xxx=xxx;
    //...
    return jQuery;
})(); // This executes the inline function and assign `jQuery` with the return value???
//... })(window);
Run Code Online (Sandbox Code Playgroud)

这更像是以下内容:

function define_jQuery(){
    // Inside this function defines jQuery and return it?
    var jQuery=function(selector,context){
        return new jQuery(selector,context); //simplified
    };
    jQuery.xxx=xxx;
    //...
    return jQuery;
}

//(function(window,undefined){
var jQuery=define_jQuery(); // This executes the inline function and assign `jQuery` with the return value???
//... })(window);
Run Code Online (Sandbox Code Playgroud)

这样做不会更简单:

//(function(window,undefined){
var jQuery=function(selector,context){
    return new jQuery(selector,context); //simplified
};
jQuery.xxx=xxx;
//...
//... })(window);
Run Code Online (Sandbox Code Playgroud)

rob*_*ich 10

分别回答这些问题:

  1. 为什么要window传入?因为在JavaScript中解除引用变量是很痛苦的.传递实例意味着您没有必要.通常,机制如下所示:

    (function (window, document, $) {
    }(window, window.document, jQuery));
    
    Run Code Online (Sandbox Code Playgroud)

    在这种情况下,不需要去全局范围来取消引用这三个中的任何一个(并且jQuery可以在.noConflict()引导中).

  2. 这是有效的JavaScript : undefined = 2;. 我承认这是非常愚蠢的,但这是可能的.但是如果一个函数接受一个函数而不是传递一个参数,那么人们就会确信它是真实的,undefined而不是它被黑客攻击的副本.

  3. 从前一个函数返回jQuery允许方法链接:$('#sel').func1().func2().这是可能的,因为func1可能看起来像这样:

    jQuery.fn.func1 = function () {
        return $(this).each(function () {
            // do something fabulous
        };
    };
    
    Run Code Online (Sandbox Code Playgroud)

return $(this).bla_de_bla() 是短手:

    $(this).bla_de_bla(..);
    return $(this);
Run Code Online (Sandbox Code Playgroud)

它还假设.bla_de_bla()也返回 $(this)

编辑:修改#3注意它最好是链接而不是环绕.noConflict()并错误命名$.