jquery構造函數分析

  jquery是面向對象的寫法也有構造函數,每次調用jquery方法是就會實例化一個jqeury對象,但是jQuery的寫法卻非常高明值得我們學習。

  js雖然不是面向對象的語言,卻又很多面向對象的寫法,這裏推薦大家看一下圖靈的《javascript高級程序設計》中的面向對象的程序設計部分。在衆多方法中比較常見的寫法是構造加原型方式,下面舉例:

var Person=function(name,age){
   this.name=name;
   this.age=age;
}
Person.prototype={
  constructor:Person,
  init:function(msg){
    this.say(msg);
  },
  say:function(msg){
  alert(this.name+'說'+msg);
  }
};
var tom=new Person('tom',23); 
tom.init('你好');// tom說你好

那再來看看jQuery的構造函數吧

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},

可以看到在jQuery真正的函數是init方法,當我們調用jquery時會new init() 而不是 new jQuery() .

jQuery.fn是啥呢,在後面我們會看到這樣一句代碼
jQuery.fn = jQuery.prototype = {...

這樣就很好理解了,其實jQuery.fn就是原型對象也就是說在jQuery原型裏面有一個init方法,這個方法是真正的構造函數。這樣寫的好處就是不需要在寫$().init()這樣的操作,直接就初始化了,但是還有一個問題就是既然init纔是構造函數那我們寫在jQuery上面的那麼方法實例不是不能調用嗎?init的實例化自然只能調用init的方法啦,往後看到這樣一句代碼

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

之前講過jQuery.fn=jQuery.protype,這就意味着jQuery的原型對象賦給了init的原型,這樣jQuery的原型方法自然init也就都有了,通過這樣構造方式S使得使用jQuery方法非常簡單既不需要new jQuery()的操作也不需要手動初始化就行調用普通函數一樣簡單。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章