jQuery.extend和jQuery.fn.extend

时间:2013-01-12 15:27:38

标签: javascript jquery

我正在用extend进行一些测试,在我做了一些观察后我感到有些困惑。第一次观察:

console.log($.extend === $.fn.extend); // trure
// and since $ === jQuery then ...
console.log(jQuery.extend === jQuery.fn.extend); // true

到目前为止这么好,不是吗?鉴于上述结果,我认为这样做:

// SNIPPET 1
$.extend({
   log: function(m) {
      console.log(m);
   }
});

和此:

// SNIPPET 2
$.fn.extend({
   log: function(m) {
      console.log(m);
   }
});

是一样的。但实际上事情的方式却截然不同。事实上,如果您运行SNIPPET 1然后执行:

$("body").log("whatever");

您收到错误(未定义日志)。但你可以这样做:

$.log("whatever");

如果您改为运行SNIPPET 2,则会得到相反的结果,即:

$("body").log("whatever"); // this will work
$.log("whatever"); // this won't

到底是什么?我很欣赏.extend扩展了执行它的对象($ vs $.prototype)这一事实,但我没有得到的是它是如何做到的!特别考虑到以下事实:

$.extend === $.fn.extend // true

功能相同!!它如何产生2种不同的结果?

1 个答案:

答案 0 :(得分:1)

函数this内部将有所不同。在第一种情况下,它将是$,在第二种$.fn中。

查看source code

jQuery.extend = jQuery.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // ...

    // extend jQuery itself if only one argument is passed
    if ( length === i ) {
        target = this;
         --i;
    }

    // ...
};

Learn more about this