jQuery1.3.2 源码学习6 size 和 get 函数

96 // Start with an empty selector

97 selector: "",

98

99     // The current version of jQuery being used

100    jquery: "1.3.2",

101

102 // The number of elements contained in the matched element set

103 size: function() {

104    return this.length;

105 },

106

107 // Get the Nth element in the matched element set OR

108 // Get the whole matched element set as a clean array

109 get: function( num ) {

110    return num === undefined ?

111

112        // Return a 'clean' array

113        Array.prototype.slice.call( this ) :

114

115        // Return just the object

116        this[ num ];

117 },

 

97 行开始,一直到 538 行,定义了 jQuery 对象所共享的方法和属性。

 

97 行在对象上定义了一个属性 selector,用来表示当前使用的选择器

110 行在对象上定义了一个属性 jquery,表示当前的 jQuery 版本

103 行定义了 jQuery 对象的 size 方法,由于 jQuery 对象就是一个仿数组的对象,所以直接返回对象的 length 属性,就是查询结果中的对象数量。

 

109 行到 117 行,定义了 get 方法,用来返回指定下标的查询对象。

其中 110 行用来判断是否传递了下标参数,如果传递了下标参数,那么参数 num 就不等于 undefined,注意,这里使用了 === 用来判断是否完全相等。

如果传递了参数,那么在 116 行通过属性索引器 [] 来获取指定下标的对象。

如果没有传递参数,那么使用第 113 行处理。

113 行首先通过 Array.prototype 找到 Array 的原型对象,因为数组的方法都是通过这个原型对象提供的。然后,调用这个原型对象上的 slice 方法,调用这个方法的时候还使用了 call,用来将第一个参数作为方法的 this 参数传入,也就是取得当前查询结果对象上,数组的 slice 可以传递两个参数,第一个参数表示起始下标,第二个参数表示结束下标,如果两个都没有提供,那么起始下标就是 0, 结束下标就是 lengthSlice 将返回从起始下标到结束下标 – 1 的所有属性,并将结果封装为一个新的真正的数组对象。

 

原文地址:https://www.cnblogs.com/haogj/p/1718670.html