码迷,mamicode.com
首页 > Web开发 > 详细

深入了解jQuery之整体架构

时间:2017-05-16 17:57:43      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:obj   something   ima   nbsp   原型   源码解析   blog   代码   sel   

本文是在阅读了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

 

 配张思路图:

技术分享

 

深入了解jQuery之整体架构

标签:obj   something   ima   nbsp   原型   源码解析   blog   代码   sel   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!