×

jQuery.fn和jQuery.prototype区别介绍

作者:Terry2017.02.07来源:Web前端之家浏览:10534评论:0
关键词:JQueryJS
近期在读jQuery的源码。

发现这里有个东西很难理解。

这里的 jQuery , jQuery.fn , jQuery,fn,init ,jQuery,prototype 都代表什么。

来看下jQuery的源码是怎么样定义的:
复制代码 代码如下:

(function( window, undefined ) {

var jQuery = (function() {
// 构建jQuery对象
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
}

// jQuery对象原型
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
// something to do
}
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

// 合并内容到第一个参数中,后续大部分功能都通过该函数扩展
// 通过jQuery.fn.extend扩展的函数,大部分都会调用通过jQuery.extend扩展的同名函数
jQuery.extend = jQuery.fn.extend = function() {};

// 在jQuery上扩展静态方法
jQuery.extend({
// something to do
});

// 到这里,jQuery对象构造完成,后边的代码都是对jQuery或jQuery对象的扩展
return jQuery;

})();

window.jQuery = window.$ = jQuery;
})(window);

这里我们可以看到:
复制代码 代码如下:

var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
}

jQuery 其实jQuery.fn.init()返回一个对象。那么jquery.fn.init()返回的又是什么呢?
复制代码 代码如下:

jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
// something to do
}
};

就是从这里来的,一个javascript对象。

这里有个问题。
复制代码 代码如下:

jQuery.fn = jQuery.prototype

那么就是 将jQuery 的原型对象赋值给了 jQuery.fn。

再看下面:
复制代码 代码如下:

jQuery.fn.init.prototype = jQuery.fn;

看到这里我有一个想法。就是 将jQuery.fn 给了 jQuery.fn.init.prototype.

那么在这之前jQuery.fn.init.prototype.是什么?

是不是没有?这个时候它的原型是{};

那么为了可以去调用init外面的方法。就做了一个处理。

将jQuery.fn 赋值给jQuery.fn.init.prototype.这样的话,

jQuery.fn.init.prototype的原型也就是jQuery的原型对象就是 jQuery.fn ( 注意jQuery = function(return new jQuery.fn.init()))。

赋值了以后。在调用的时候,当init中没有方法的时候,就会去原型函数中调用。

那么这样的话。

你可能会想到这样一个东东:
复制代码 代码如下:

jQuery.extends()
jQuery.fn.extends()

我想你应该明白它们的区别了吧。

jQuery.extends()是直接扩展jQuery.而jQuery.fn.extends(),很明显是扩展的原型。

这就是为什么jQuery.fn.extends()中的大部分方法来自己于jQuery.extends()。

这里又将 jQuery.fn 赋值给了 jQuery.fn.init.prototype.

那么就有这样的一个关系:
复制代码 代码如下:

jQuery.prototype = jQuery.fn = jQuery.fn.init.prototype

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/svg1486396800909.html

网友评论文明上网理性发言已有0人参与

发表评论: