jquery源码解析:jQuery工具方法详解2

jQuery的工具方法,其实就是静态方法,源码里面就是通过extend方法,把这些工具方法添加给jQuery构造函数的。

jQuery.extend({

  ......  

  type: function( obj ) {    //$.type(),判断类型
    if ( obj == null ) {   //null,undefined
      return String( obj );    //返回null,undefined字符串
    }     //core_toString = {}.toString 
    return typeof obj === "object" || typeof obj === "function" ?
      class2type[ core_toString.call(obj) ] || "object" :     //number,string等包装类型,typeof判断是object,所以进入到toString判断,最终返回number,string

        typeof obj;       //基本类型,number,string直接用typeof.
  }, 

  isPlainObject: function( obj ) {   //判断是否是对象自变量,{},new Object
    if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
      return false;    //dom节点,window等是object,但是不是对象自变量。
    }

    try {     //window.location是object,core_hasOwn是{}.hasOwnProperty(自己的属性,不是原型的属性)
      if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
        //isPrototypeOf只存在object.prototype对象中,core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" )这句话的意思就是:obj.constructor.prototype是否有isPrototypeOf属性,从上可知,只有object.prototype有,所以只有object.prototype才返回真。比如,我传入一个Person(构造函数),它的原型没有isPrototypeOf属性,所以返回false。Person不是对象自变量。

        return false;
      }//在火狐20以下版本,如果操作window.location.constructor 多次,会抛错
    } catch ( e ) {
      return false;
    }

    return true;
  },

  isEmptyObject: function( obj ) {  //{},[],对象自身下没有属性和方法就返回true。function Person(){} ;var person = new Person(),返回true

    var name;
    for ( name in obj ) {     //系统自带的属性和方法不会for in打印出来。
      return false;
    }
    return true;
  }, 

  parseHTML: function( data, context, keepScripts ) {   //解析字符串为数组节点,比如:"<li></li>" -> [li元素]

    //keepScripts 为true,可以解析script,false不能解析script标签
    if ( !data || typeof data !== "string" ) {  
      return null;
    }
    if ( typeof context === "boolean" ) {   //如果没有第二个参数
      keepScripts = context;
      context = false;
    }
    context = context || document;

    var parsed = rsingleTag.exec( data ),     //假如是单标签"<li></li>"
    scripts = !keepScripts && [];

    if ( parsed ) {    //直接创建这个元素,然后放进数组中返回
      return [ context.createElement( parsed[1] ) ];
    }

    parsed = jQuery.buildFragment( [ data ], context, scripts );

     //如果keepScripts为false,则会传入空数组scripts ,buildFragment会判断data中是否有script,如果有就放入空数组,变成[script],没有就返回[]。如果keepScripts为true,就传入false,buildFragment不对它做改变,还是false.

    if ( scripts ) {
      jQuery( scripts ).remove();   //移除script标签
    }

    return jQuery.merge( [], parsed.childNodes );
  },//eval可以解析json字符串,任何格式的都可以,危险性提高。JSON.parse()只能解析标准的json字符串,性能好于eval。 

  parseXML: function( data ) {  //解析xml字符串为xml文档。
    var xml, tmp;
    if ( !data || typeof data !== "string" ) {
      return null;
    }

    try {
      tmp = new DOMParser();    //IE6-8使用ActiveXObject来解析
      xml = tmp.parseFromString( data , "text/xml" );

      //IE9下,如果xml字符串不是正常的xml标签,会报错。其他浏览器不会报错,会在返回的xml文档中生成parsererror节点
    } catch ( e ) {
      xml = undefined;
    }

    if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
      jQuery.error( "Invalid XML: " + data );
    }
    return xml;
  }, 

  globalEval: function( code ) {   //把局部变量变成全局变量,比如:"var a=1"。
    var script,
    indirect = eval;//eval既是关键字,又是window下的属性。直接写eval(code),浏览器会当做js关键字使用,出错。所以赋值一下,就会把eval当做window的属性。

    code = jQuery.trim( code );      //code必须为字符串形式

    if ( code ) {
      if ( code.indexOf("use strict") === 1 ) {  //严格模式下,不能使用eval.
        script = document.createElement("script");
        script.text = code;
        document.head.appendChild( script ).parentNode.removeChild( script );
      } else {
        indirect( code );
      }
    }
  },  

  camelCase: function( string ) {   //转驼峰,IE下:-ms-transform -> msTransform,而其他-moz-transform-> MozTransform,所以先把-ms-替换成ms-,这样就只会转成msTransform,m不会大写了。而其他浏览器需要大写
    return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
  },

  ......

})

加油!

时间: 2024-08-04 15:51:15

jquery源码解析:jQuery工具方法详解2的相关文章

十七.jQuery源码解析之入口方法Sizzle(1)

函数Sizzle(selector,context,results,seed)用于查找与选择器表达式selector匹配的元素集合.该函数是选择器引擎的入口. 函数Sizzle执行的6个关键步骤如下: 1.解析选择器表达式,解析出块表达式和关系符. 2.如果存在位置伪类,则从左向右查找: a.查找第一个块表达式匹配的元素集合,得到第一个上下文元素集合. b.遍历剩余的块表达式和块间关系符,不断缩小上下文元素集合. 3.否则从右向左查找: a.查找最后一个块表达式匹配的元素集合,得到候选集,映射集

jQuery源码学习3——工具方法篇

基本工具方法结构如下: jQuery.extend({ init:function(){}, each:function(){}, className:{ add:function(){}, remove:function(){}, has:function(){}, }, swap:function(){}, css:function(){}, curCSS:function(){}, clean:function(){}, expr:{}, token:[], find:function()

jQuery源码学习5——工具方法之attr parents sibling clean

(1).attr attr: function(elem, name, value){ var fix = { "for": "htmlFor", "class": "className", "float": "cssFloat", innerHTML: "innerHTML", className: "className" }; if ( fix

JQuery源码解析-JQuery的工具方法(3)

这篇文章主要对下面这几个方法进行解释 error();抛出异常 parseHTML():解析节点 parseJSON():解析JSON parseXML:解析XML noop():空函数 globalEval():全局解析JS camelCase():转驼峰 nodeName():是否为指定节点(内部) error:方法: error方法的作用是抛出一个自定义异常,内部直接调用了原生解释的throw new Error error: function( msg ) { throw new Err

JQuery源码解析-JQuery的工具方法(2)

这篇对下面的方法进行讲解: isFunction():是否为函数 isArray():是否为数组 isWindow():是否为window isNumeric()是否为数字 type():判断数据类型 isPlainObject():是否为对象自变量 isEmptyObject():是否为空的对象 isFunction方法: 这个方法很简单,判断对象是否为函数,返回bool类型,看一下源码: // See test/unit/core.js for details concerning isFu

JQuery源码解析-JQuery的工具方法(5)

下面对最后这几个方法进行讲解. guid():唯一表示(内部) proxy():改变this指向 access(): 多功能值操作 now():当前时间 swap():css交换(内部) guid: 这个属性是对事件进行控制的,例如每次对dom元素进行绑定事件的时候,会通过这个属性进行绑定,这个属性每次自增,产生一个唯一的标示,所以对dom元素进行事件解绑等操作的时候,通过这个属性就可以找到. 源码: // A global GUID counter for objects guid: 1, p

JQuery源码解析-JQuery的工具方法(4)

下面对这些方法进行讲解 each():遍历集合 trim():去前后空格 makeArray():类数组转换真数组 inArray():数组版indexOf merge():合并数组 grep():过滤新数组 map():映射新数组 each方法: each是遍历集合用的方法,也是一个加强版的循环操作.例如: var arr = { Name: 'jam', Age: 15 }; $.each(arr, function (key, val) { console.log(key + ":&quo

guava-retrying 源码解析(停止策略详解)

一.停止策略相关类 1.停止策略接口:StopStrategy接口,只有一个抽象方法 // 是否应该停止重试.不同的停止策略有不同的实现.boolean shouldStop(Attempt failedAttempt); 2.停止策略工厂类:StopStrategies类 这是一个常量类.工厂类,用于创建停止策略对象.这个工厂类里面定义了三种停止策略,都是常量静态内部类. 该工厂类是创建停止策略的唯一途径. 二.详解三种停止策略 1.从不停止策略:NeverStopStrategy 使用这种策

guava-retrying 源码解析(阻塞策略详解)

这是一种策略,用于决定重试者应如何在重试尝试之间进行阻止.通常这只是一个thread.sleep(),但是如果需要的话,实现可能更复杂. 一.阻塞策略相关的类或接口 1.阻塞策略接口:BlockStrategy 底层默认使用来 Thread.sleep 完成线程阻塞,从而实现重试之间的等待{@link com.github.rholder.retry.WaitStrategy}.如果需要,实现可以更加复杂. 接口里面有一个实现方法,如下. 2.阻塞策略工厂类:BlockStrategies. 该

jQuery方法源码解析--jQuery($)方法(一)

jQuery方法源码解析--jQuery($)方法 注: 1.本文分析的代码为jQuery.1.11.1版本,在官网上下载未压缩版即可 2.转载请注明出处 jQuery方法: 这个方法大家都不陌生,在使用过程中,它还有另外一个名字,美元符号:$,$(...)其实就是jQuery(...); 它有很多种用法,通常都返回一个jquery对象,也可以作为$(document).ready(...);的简写形式,分析之前先看一下jQuery都有什么用法. 1.jQuery( selector [, co