jQuery源码学习笔记三

本文深入讲解jQuery对象的核心机制,包括jQuery对象如何封装DOM元素、jQuery.prototype的作用及其实现细节、常用方法如slice、map的工作原理,以及jQuery.extend的使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

还有一点,jQuery.prototype第一个阶级的能力部署就完成了。就像一个茧,jQuery对象包裹着一个或复数个DOM对象,jQuery对象的能力来自其prototype,而其prototype的方法则是jQuery.prototype的一个副本。

 

//对当前jQuery中的DOM进行slice操作,并把参数传入this.prevObject中
      slice: function() {
        return this.pushStack( Array.prototype.slice.apply( this, arguments ),
        "slice", Array.prototype.slice.call(arguments).join(",") );
      },
 //与上面差不多
      map: function( callback ) {
        return this.pushStack( jQuery.map(this, function(elem, i){
          return callback.call( elem, i, elem );
        }));
      },
//把之前放入this.preveObject的DOM数组取出来,加入现在的DOM数组中
      andSelf: function() {
        return this.add( this.prevObject );
      },
 
      domManip: function( args, table, callback ) {
        if ( this[0] ) {
          //如果jQuery对象有DOM元素,则取得其文档对象,调用其createDocumentFragment方法
          var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
          //这里的args恒为arguments对象,用jQuery.clean获得纯DOM元素数组
          scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
          first = fragment.firstChild;
 
          if ( first )
            for ( var i = 0, l = this.length; i < l; i++ )
              //callback传入一个元素与一个文档
              callback.call( root(this[i], first), this.length > 1 || i > 0 ?
            fragment.cloneNode(true) : fragment );
          if ( scripts )
            jQuery.each( scripts, evalScript );
        }
 
        return this;
        //root用于检测当前元素是否为table,是就检测tbody是否存在,没有则创建
        function root( elem, cur ) {
          return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
            (elem.getElementsByTagName("tbody")[0] ||
            elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
            elem;
        }
      }
    };
//把jQuery.prototype的能力加持到jQuery.prototype.init.prototype上
   jQuery.fn.init.prototype = jQuery.fn;

 

至此,jQuery对象第一阶级的能力就告一段落,要不对象体就很长。下面添加新的能力时就用jQuery.extend求添加,就像Prototype 的Object.extend,mootool的Native.implement,Base2的Base.extend,Ext的apply,凡此种 种,把一个属性包或独立的方法名与方法体作为参数加入目标对象中。因为光是在对象体搞(这里是原型),没有私有变量可言,有时我们很需要这些作为胶水在连 接我们的方法,因此打散写有打散写的好处。更何况,jQuery类库都是整个包围在一个闭包中,这些散乱的函数与变量不会逃逸到外面去,与我们的业务逻辑 中用的函数或变量发生命名冲突。

 

//jQuery的能力扩展的核心函数
//这要求存在继承者与授与者两方,一般来说继承者在左,授与者在右,授与者通常是一个简单的属性包
jQuery.extend = jQuery.fn.extend = function() {
  // copy reference to target object
  var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

  // Handle a deep copy situation
  if ( typeof target === "boolean" ) {//如果第一个参数是布尔值
    deep = target;
    target = arguments[1] || {};//设置继承者
    // skip the boolean and the target
    i = 2;
  }

  // Handle case when target is a string or something (possible in deep copy)
  if ( typeof target !== "object" && !jQuery.isFunction(target) )
    target = {};
  //如果没有指定要继承能力的对象,则扩展到自身
  // extend jQuery itself if only one argument is passed
  if ( length == i ) {
    target = this;
    --i;
  }

  for ( ; i < length; i++ )
  // Only deal with non-null/undefined values
    if ( (options = arguments[ i ]) != null )
    // Extend the base object
      for ( var name in options ) {
        var src = target[ name ], copy = options[ name ];
             
        // Prevent never-ending loop
        if ( target === copy )
          continue;
        //如果是深复制,某对象的属性也是对象并且不是HTMLElement,则把它逐一分解拷到继承者
        // Recurse if we're merging object values
        if ( deep && copy && typeof copy === "object" && !copy.nodeType )
          target[ name ] = jQuery.extend( deep,
        // Never move original objects, clone them
        src || ( copy.length != null ? [ ] : { } )
        , copy );

        // Don't bring in undefined values
        else if ( copy !== undefined )
          target[ name ] = copy;

      }

  // Return the modified object
  return target;
};

 

定义几个位于闭包的顶层变量,准备新一轮的功能扩展

 

// exclude the following css properties to add px
//将转换成px单位
var    exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
// cache defaultView
defaultView = document.defaultView || {},
toString = Object.prototype.toString;
//第二轮能力扩展,这次是添加一系列静态方法
jQuery.extend({
noConflict: function( deep ) {
  //引入jQuery类库后,闭包外面的window.$与window.jQuery都储存着一个函数,
  //它是用来生成jQuery对象或在domReady后执行里面的函数的
  //回顾最上面的代码,在还没有把function赋给它们时,_jQuery与_$已经被赋值了,
  //因此它们俩的值一定必然是undefined
  //因此这种放弃控制权的技术很简单,就是用undefined把window.$里面的jQuery系的函数清除掉
  //这时Prototype或mootools的$就可以明门正娶了
  window.$ = _$;//相当window.$ = undefined
  //如果连你的程序也有一个叫jQuery的东西呢,jQuery可以大方地连这个也让渡出去
  //这时就要为noConflict添加一个布尔值,为true
  if ( deep )
  //但我们必须用一个东西要接纳jQuery对象与jQuery的入口函数
  //闭包里面的东西除非被window等宿主对象引用,否则就是不可见的
  //因此我们把闭包里面的jQuery return出去,外面用一个变量接纳就是
    window.jQuery = _jQuery;//相当window.jQuery = undefined
  return jQuery;
},
 
//外国近年来新发现的检测技术toString
isFunction: function( obj ) {
  return toString.call(obj) === "[object Function]";
},
 
isArray: function( obj ) {
  return toString.call(obj) === "[object Array]";
},
 
// check if an element is in a (or is an) XML document
//检测是否为XML的文档对象
isXMLDoc: function( elem ) {
  return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
    !!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
},
 
// Evalulates a script in a global context
//把一段文本解析成脚本,利用script元素的text属性
globalEval: function( data ) {
  if ( data && /\S/.test(data) ) {
    // Inspired by code by Andrea Giammarchi
    // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
    var head = document.getElementsByTagName("head")[0] || document.documentElement,
    script = document.createElement("script");
    //自行创建一个script元素,如果支持text属性则直接赋,不支持就用标准方法在里面添加文本
    script.type = "text/javascript";
    if ( jQuery.support.scriptEval )
      script.appendChild( document.createTextNode( data ) );
    else
      script.text = data;
    // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
    // This arises when a base node is used (#2709).
    head.insertBefore( script, head.firstChild );
    head.removeChild( script );
  }
},
//检测elem的nodeName是否等于第二个参数name
nodeName: function( elem, name ) {
  return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
  var name, i = 0, length = object.length;
   
  if ( args ) {
    if ( length === undefined ) {
      //如果是对象就对其值调用方法,如果调用函数没有返回值或返回false就跳出循环
      for ( name in object )
        if ( callback.apply( object[ name ], args ) === false )
          break;
    } else
    //如果是数组
      for ( ; i < length; )
        if ( callback.apply( object[ i++ ], args ) === false )
          break;
    //同上,只不过没有传入第三个参数
    // A special, fast, case for the most common use of each
  } else {
    if ( length === undefined ) {
      for ( name in object )
        if ( callback.call( object[ name ], name, object[ name ] ) === false )
          break;
    } else
      for ( var value = object[0];
    i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
  }
   
  return object;
},
//用于返回各种属性
prop: function( elem, value, type, i, name ) {
  // Handle executable functions
  if ( jQuery.isFunction( value ) )
    value = value.call( elem, i );
   
  // Handle passing in a number to a CSS property
  return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
    value + "px" :
    value;
},

接着下来就是对样式的操作了,样式在WEB开发中非常重要,我留在下一节重点讲

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值