首先看一下在jQuery1.7.1中定義的原型屬性和方法有哪些?


首先是constructor屬性
相信熟悉js面向對象部分的開發人員都熟悉,就是用來返回對象屬性創建的函數,舉個簡單的例子:
function Person(){};
var person=new Person();
alert(person.constructor); //function Person(){}
我們寫繼承的時候喜歡把所有的原型屬性和方法放在一個單獨的對象字面量中,這樣就會導致constructor屬性與“實際”指向不符合例如:
function Person(){
}
Person.prototype={
say:function(msg){
alert(msg);
}
}
var person=new Person();
person.say('hello');
alert(person.constructor); //function Object(){[native code]}
這個時候的指向就會變化因為字面量對象是Object的一個實例自然constructor屬性就會執行Object為了糾正這個“錯誤”通常需要手動修改回來這就是源碼,源碼中constructor:jQuery的解釋
selector屬性
selector屬性對於使用jquey作為js庫來說沒有用處它主要是用於開發基於jquery的插件或者改造使用,該屬性會返回獲取當前的jquery對象的選擇器字符串,例如:
var obj=$('div a');
console.log(obj.selector);//'div a'
jquery屬性
該屬性返回當前使用的jQuery版本
console.log($('body').jquery); //1.7.1
length屬性
該屬性返回jquery對象包含的元素個數例如:
console.log ( $('body') .length); //1
這4個屬性源碼如下:
constructor: jQuery, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.1", // The default length of a jQuery object is 0 length: 0,
size方法
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
該方法就是返回jquery對象的length屬性兩者而言推薦使用length屬性,可以減少不必要的函數調用開銷
toArray方法
toArray: function() {
return slice.call( this, 0 );
},
把jQuery集合中所有DOM元素恢復成一個數組。
alert($('li').toArray());
[<li id="foo">, <li id="bar">]
首先這裡的slice方法在jQuery的構造函數裡面已經被保留下來,就是Array的原型方法
// Save a reference to some core methods 87 toString = Object.prototype.toString, 88 hasOwn = Object.prototype.hasOwnProperty, 89 push = Array.prototype.push, 90 slice = Array.prototype.slice, 91 trim = String.prototype.trim, 92 indexOf = Array.prototype.indexOf,
通過call方法實現對象冒充,傳入參數0表示不進行截取,由於此方法會返回一個 clean array 也就是純數組這樣就實現了從jquery對象到純數組的轉變,在以後遇到其他類數組形式時也可以采用此方法進行轉換例如:
<!doctype html>
<html>
<head>
<meta charset='utf-8'/>
<title>jQuery源碼分析-原型屬性和方法</title>
</head>
<body>
<div>
</div>
<div></div>
</body>
<script src='jquery-1.7.1.js'></script>
<script>
var divs=document.getElementsByTagName('div');
console.log(divs); //[div, div]
alert(divs instanceof Array); //fasle
alert(Array.prototype.slice.call(divs,0) instanceof Array); //true
</script>
</html>
所以學習jqeury源碼除了對使用jquery有幫助之外還能學到很多js的使用技巧
get方法
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
此方法的作品是從jquery對象的元素數組中找到其中的某一個並且返回js原聲node元素對象而不是jquery對象,這是跟eq方法不同的地方 ,此方法接受一個參數如果參數不存則調用toArray方法返回包涵所有元素的數組,如果是大於0的數直接通過下下標的方式獲取即可如果是負數則通過與長度相加獲得我們寫某些方法需要支持正負數下標的一個很好的方法。如果寫的不是數字,或者超過當前對象所包含的元素長度會返回undefined.
以上所述就是本文的全部內容了,希望大家能夠喜歡。