jQuery源码分析

来源:互联网 发布:联通有网络机顶盒吗 编辑:程序博客网 时间:2024/06/07 05:36

JQuery源码分析

测试环境

工具/版本说明 版本号 备注 jQuery 2.1.1 sublime 3

1:源码结构之对象添加属性(后期持续更新中)

jQuery = function( selector, context ) {    return new jQuery.fn.init( selector, context );}jQuery.fn = jQuery.prototype = {    constructor: jQuery,}//快速匹配正则 不加g;不光匹配整体项还会匹配到子项rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,init = jQuery.fn.init = function( selector, context ) {    var match, elem;        // HANDLE: $(""), $(null), $(undefined), $(false)    if ( !selector ) {//输入错误直接返回对象        return this;//this是对象    }    // Handle HTML strings    if( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3){//创建标签,复杂的创建标签        //$('<li>') $('<li>1</li><li>2</li>')        match = [ null, selector, null ];        1match = [ null, '<li>', null ];//$('<li>')        2match = [ null, '<li>1</li><li>2</li>', null ];//$('<li>1</li><li>2</li>')    }else{//选择标签 及一个不常见的创建标签$('<li>hello')        //$('#div1') $('.box') $('div') $('#div1 div.box') $('<li>hello')//$('#div1') $('<li>hello')用正则可以匹配到结果;剩下匹配不到结果        match = rquickExpr.exec( selector );//exec:找到匹配数组集        1match=null;// 匹配不到结果:$('.box') $('div') $('#div1 div.box')        2match=['#div1',null,'div1'];//$('#div1')        3match=['<li>hello','<li>',null];//$('<li>hello')=$('<li>')    }if( match && (match[1] || !context)){//match为true:创建标签或选择id时候    if( match[1] ){// HANDLE: $(html) -> $(array) 创建标签        context = context instanceof jQuery ? context[0] : context;//获得原生的document        //merge合并数组;对外只是数组合并;对内json进行合并;json需要特殊性        jQuery.merge( this, jQuery.parseHTML() );//jQuery.parseHTML()字符串转换为节点数组        //HANDLE: $(html, props)创建标签带属性,例:$('<li>',{ title:'hehe' , html:'猪' , css:{background:'red'} } ).appendTo('ul')        //rsingleTag匹配单标签 var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);        //<li> <li></li>这是单标签;其它都不是        //第二个参数必须是对象字面量 JSON形式        if(rsingleTag.test( match[1] ) && jQuery.isPlainObject( context )){             for ( match in context ) {                //this[ match] 指的是{title:'hehe',html:'猪'}内的title和html                if ( jQuery.isFunction( this[ match ] ) ) {//判断是否是函数                    this[ match ]( context[ match ] );//函数调用:此处html方法                }else{                    this.attr( match, context[ match ] );//否则加属性                }            }        }    }else{// HANDLE: $(#id)    }}else{}   // HANDLE: $(expr, $(...))    // HANDLE: $(expr, context)    // HANDLE: $(DOMElement)    // HANDLE: $(function)    return jQuery.makeArray( selector, this );}init.prototype = jQuery.fn;

源码分析

1.1constructor

    function AAA(){}    //面向对象中两种写法是有区别的    AAA.prototype.name = "hello";//name与age只是向原型上进行添加处理    AAA.prototype.age = 30;    AAA.prototype = {//覆盖原型;指向出现问题        name:"hello",        age:30    }    console.log(AAA.constructor)    console.log(AAA.prototype)

1.2属性操作原理浅要分析

<ul>    <li></li>    <li></li>    <li></li></ul>// jquery操作$(function(){    console.log($('li').css('background','red'));});//原生操作var aLi=document.getElementsByTagName('li');//$('li');for (var i =0; i < aLi.length; i++) {//.css('background','red');    aLi[i].style.background='red';};//jquery内原理操作分析this = {//$('li');面向对象中变量是局部的;在$()中做了一个这样的处理    0='li',    1='li',    2='li',    length=3//这里的length就是jQuery.prototype 的一个属性;因此jquery对象有和数组差不多的功能;length默认长度0};//JSON无法进行for循环,只能进行for in//但是这时的this可以进行for循环,因为以下标表示,且有length属性for(var i=0;i<this.length;i++){    this[i].style.background='red';//this[i]原生的li}

1.3parseHTML解析

$(function(){    //script标签需要转义;否则默认认为是结束标签    var str='<li>1</li><li>2</li><li>3</li><script>alert(4)<\/script>';    //parseHTML第二个参数默认上下文    //第三个参数代表script是否可以添加;默认是false//parseHTML返回的数组    var arr=jQuery.parseHTML(str,document,true);//['li','li','li']    $.each(arr,function(i){        $('ul').append(arr[i]);    });})

1.4merge

//数组合并    var arr1=['a','b'];    //此合并成为一个json    var arr1={        0:'a',        1:'b',        length:2    }    var arr2=['c','d'];    console.log($.merge(arr1, arr2))
0 0
原创粉丝点击