未分类

jQuery回顾(2)

jQuery源码

整体架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(function(global,factory){
factory(global)
})(typeof window !== "undefined" ?window : this,function(window,noGlobal){//当全局为window时在window中起作用,不为window时,传入的执行上下文起作用

//各种函数
function jQuery(selector){
return new jQuery.prototype.init();
}

jQuery.prototype.init = function(){
this[0] = document.getElementsByTagName(selector)[0];
this.length = 1;
}
jQuery.prototype.css = function(){
console.log('css');
return this;//链式调用,必返回init对象
}
jQuery.prototype.init.prototype = jQuery.prototype;//******至关重要******
})

$()是一种函数执行的形式,$代表jQuery,与调用jQuery()一样
jQuery返回jQuery.prototype.init创建的对象

init初始化元素
可传参数
1.$(‘’)
2.string
在判断string时分几种方法不一一细说了
有一个match方法正则匹配两部分

1
参数[要匹配的,正则第一部分匹配标签<>,第二部分匹配id]

3.dom
4.function

1
return root.ready !== undefined?root.ready(selector):selector(jQuery);

5.$($())

1
jQuery.fn = jQuery.prototype

1
2
3
init = jQuery.fn.init = function(selector,context,root){//选择器,上下文,root
//...
}

$.extend对象合并(浅拷贝)

eg:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var obj1 = {
person1:{
name:'dg',
fun:function(){
console.log('hello');
}
}
}
var obj2 = {
person2:{
name:'cg',
fun:function(){
console.log('world')
}
}
}

$.extend(obj1,obj2);//若传一个参数,则将该参数合并到extend函数上
console.log(obj1.person2.name)//cg

$.fn.extend(obj1)//合并到jQuery.prototype上
$.extend = $.fn.extend

四种情况
1.$.extend(obj)
len = 1
target = $;//this
i = 0;

2.$.extend(obj1,obj2)
len = 2
target = obj1;
i = 1;
//以上两种为深拷贝

3.$.extend(true,obj1);//传true变为深拷贝
len = 2
target = obj1;//先等于true(i=1)后变为obj1(i=2),此时i = length所以是单纯一个对象(i–并且将target变为调用的对象$.fn)
i = 2;

4.$extend(true,obj1,obj2);
len = 3
target = obj1;
i = 2