我嘗試創建一些基於類的jQuery風格,如下面的代碼。爲什麼jQuery使用「new jQuery.fn.init()」來創建jQuery對象,但我不能?
myClass = window.myClass = function(x, y)
{
return new myClass.fn.init(x, y);
};
myClass.fn = myClass.prototype =
{
init: function(x, y)
{
// logic for creating new myClass object.
}
};
我不明白爲什麼jQuery的使用new關鍵字,因爲從我的實驗創建它的類,JavaScript的始終創建myClass.init對象,而不是MyClass的對象。但是,我嘗試刪除myClass構造函數中的新關鍵字。但它仍然沒有改變。你能解釋爲什麼jQuery可以做到這一點,但我不能或給我一些代碼在init函數中使用?
順便說一句,我可以使用下面的代碼而不是jQuery樣式代碼來創建相同的對象。我的代碼& jQuery代碼有什麼不同?使用jQuery風格有什麼好處嗎?
myClass = window.myClass = function(x, y)
{
this.init(x, y);
};
myClass.fn = myClass.prototype =
{
init: function(x, y)
{
this.x = x;
this.y = y;
}
};
PS。我喜歡將初始邏輯分解爲函數的編寫代碼,因爲使用我的代碼的其他人(如我的下面的代碼)很容易覆蓋此函數。
// override init function of myClass
myClass.fn._old_init = myClass.fn.init;
myClass.fn.init = function()
{
// logic for doing something before init
this._old_init();
// logic for doing something after init
};
感謝,
,因爲我剛剛發現,jQuery的使用這個語句(jQuery.fn.init.prototype = jQuery.fn)給了init函數jQuery的原型後實例你的回答是真實的。然而,你的回答和你的例子並沒有解決我的問題,爲什麼jQuery使用這種風格來創建jQuery對象。 – 2009-12-07 07:37:15
jQuery可能使用這種技術將構造函數與通用包裝函數('jQuery()')分開。他們可以做到這一點,這可能是一個很早就在jQuery開發中做出的決定,並沒有改變,因爲它似乎有效地工作...... – James 2009-12-07 09:57:16
@JP - 同意這可能是對早期決定的回憶 – 2009-12-07 17:54:13