get: function( num ) {
// Watch for when an array (of elements) is passed in
标记a if ( num && num.constructor == Array ) {
// Use a tricky hack to make the jQuery object
// look and feel like an array
this.length = 0;
[].push.apply( this, num );
标记b return this;
} else
标记1 return num == undefined ?
// Return a 'clean' array
jQuery.map( this, function(a){ return a } ) :
// Return just the object
this[num];
},
原型上get方法
$(‘div’).get(num)
标记1开始解读
如果a不是是数组对象就是 num你要获取的那个div的下标 0 1 2等 因为 $(’'div) = {0:div1,1:div2,length:2}是类数组对象 如果没穿参数num =
undefinded那么 返回的就是–jQuery.map( this, function(a){ return a } )
$(‘div’)类数组对像映射的数组对象 里面保存的是【div1,div2】
标记a --标记b解读 如果参数是数组[]
就把$('div).length = 0 这样再执行[].push方法时就会吧 $('div)里的数据忽略
伪代码 $(‘div’) = {} $(‘div’).length = 0
然后执行 [].push.apply ( $(‘div’),[1,2,3,4])
return this 得到的就是{0:1 , 1:2 , 2:3,3:4, length:4}
一般用法:$(‘div’).get(0)得到第一个div元素 或者不加参数返回数组对象【div1,div2…】
加深理解
当传的参数num是数组时,this.length = 0 的目的是是为了用数组中的数据覆盖掉this对象的数据
function push(){
var length = this.length
for(i=0;i < arguemnts.length;i++)
this[length+i] = arguemnts[i]
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="aa">
</div>
<div id="agree">
</div>
</body>
</html>
<script src="js/jquery-1.0.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var res = $('div')
// res.length = 0
console.log("初始的res",res);
[].push.apply(res,[1,2,3,4])
console.log(res)
</script>
没加 this.length = 0的时候结果
jQuery {0: div#aa, 1: div#agree, 2: 1, 3: 2, 4: 3, 5: 4, length: 6}
加了 this.length = 0的结果
jQuery {0: 1, 1: 2, 2: 3, 3: 4, length: 4}
没加的话就从先前的length位置开始添加参数,加了的话就从0开始添加参数,可以覆盖掉$()对象的原数据