深入了解jQuery之整体架构

本文是在阅读了Aaron艾伦的jQuery源码解析(地址:http://www.imooc.com/learn/172)后的个人体会以及笔记。在这里感谢艾伦老师深入浅出的讲解!!

先来看看如何生成一个jQuery对象,源码:

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

当我们使用jQuery('something')或者$('something')时,我们得到的是一个 jQuery.fn.init()对象。那么jQuery.fn是什么鬼?

复制代码
jQuery.fn = jQuery.prototype = {
    // jQuery版本
    jquery: version,
    constructor: jQuery, // 构造函数
    // Start with an empty selector
    selector: "",
    // The default length of a jQuery object is 0
    length: 0,
    // 省略.....
}
复制代码

jQuery.fn 实际上是jQuery构造函数的原型对象的引用!! 所以我们以后看到 jQuery.fn时,把他当成jQuery构造函数的原型对象就可以了。

知道了jQuery.fn , 接下来看看jQuery.fn.init()函数

jQuery.fn.init = function( selector, context ) {
      //  省略....
return this; };
jQuery.fn.init.prototype = jQuery.prototype; // 注意这里! 这句代码让init对象可以使用jQuery的原型方法。

这样,我们在创建jQuery对象时就不用使用new关键字了。

整体看一下源码架构:

复制代码
var $ = jQuery = function(selector,context){
    return new jQuery.fn.init(selector,context)  // 返回一个jQuery.fn.init()对象
}

jQuery.fn = jQuery.prototype = {
    constructor:jQuery,
    init:function(){
        // 省略.....
        return  this;
    }
}
jQuery.fn.init.prototype = jQuery.fn
复制代码

直观的感受一下相互之间的关系:

调用jQuery函数,我们得到的是一个jQuery.fn.init实例,这个实例的原型对象被重新指向到了jQuery函数的原型对象,所以这个实例可以使用jQuery原型对象的属性和方法,而如果我们给jQuery函数附加方法,那么这个方法就变成了静态方法

然后来看一下jQuery.fn.init函数的源码:

 View Code

 配张思路图:

原文地址:https://www.cnblogs.com/yezuhui/p/6862597.html