类似于jquery的Mole库架构分析

 仿jquery写的一个东东~

以下是jQuery 1.6.1 代码片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var jQuery = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    },
    ...
     
jQuery.fn = jQuery.prototype = {
    constructor: jQuery,
    init: function(selector, context, rootjQuery){
    }
}
 
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

jQuery对象指的是jQuery.prototype.init的实例,简单的说就是new jQuery.prototype.init。这里jQuery.prototype.init的类型是function,可以看成是一个类。

jQuery对象由以下部分组成:

  1. 挂在jQuery.prototype.init中的this上的属性或方法。
  2. 挂在jQuery.prototype.init.prototype上的属性或方法。
  3. 因为把jQuery.prototype赋值给了jQuery.prototype.init.prototype,所以挂在jQuery.prototype上的属性和方法也是jQuery对象的一部分。
  4. 通过jQuery.fn.extend({...})方式扩展的属性或方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

;(function(window, undefined) {

     //调用$或Mole构造器时,返回的实例对象共享(拥有)$原型对象的方法(因为:$.fn.init.prototype = $.fn = $.prototype;)
     var $ = window.Mole = function(selector, context) {
            return new $.fn.init(selector, context);
     };

     if (window.$ === undefined) {
            window.$ = $;
     };

     //实例对象共享的方法(原型方法)
     $.fn = $.prototype = {
           //确保constructor指针(属性)引用$
           constructor: '$',

           //初始化选择器,包括#id, .className,还有tagName.className,node节点四种格式

           init: function(selector, root) {

           },

    //判断样式类是否存在

    //显示隐藏

    //事件绑定

          //节点或HTML插入

    //坐标、宽高计算

      }

      //因为$.prototype = $.fn,所以使用new操作符调用init构造函数后返回的实例对象共享$原型的方法
      $.fn.init.prototype = $.fn;

      return $; 

})(window);

原文地址:https://www.cnblogs.com/onflying/p/3137472.html