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,用来表示当前使用的选择器 109 行到 117 行,定义了 get 方法,用来返回指定下标的查询对象。 113 行首先通过 Array.prototype 找到 Array 的原型对象,因为数组的方法都是通过这个原型对象提供的。然后,调用这个原型对象上的 slice 方法,调用这个方法的时候还使用了 call,用来将第一个参数作为方法的 this 参数传入,也就是取得当前查询结果对象上,数组的 slice 可以传递两个参数,第一个参数表示起始下标,第二个参数表示结束下标,如果两个都没有提供,那么起始下标就是 0, 结束下标就是 length。Slice 将返回从起始下标到结束下标 – 1 的所有属性,并将结果封装为一个新的真正的数组对象。 (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |