2 回答

TA貢獻1836條經驗 獲得超4個贊
我也不喜歡這種模式。他們有一個init
函數,它是所有jQuery實例的構造jQuery
函數-該函數本身只是對象創建過程的包裝器new
:
function jQuery(…) { return new init(…); }
然后,他們將這些實例的方法添加到init.prototype
對象中。該對象作為接口公開jQuery.fn
。另外,他們將prototype
jQuery函數的屬性設置為該對象-對于不使用該fn
屬性的用戶?,F在你有
jQuery.prototype = jQuery.fn = […]init.prototype
但是他們也做兩件事:
覆蓋
constructor
原型對象的屬性,將其設置為jQuery
函數公開
init
功能jQuery.fn
-自己的原型。這可能允許擴展$ .fn.init函數,但非常令人困惑
我認為他們需要/想要做所有這些事情以防萬一,但是他們的代碼是一團糟-從該對象文字開始,然后分配初始化原型。

TA貢獻1815條經驗 獲得超6個贊
如果將API視為方法的外部集合,而將jQuery函數視為包裝器,則更容易消化。
它的基本構造如下:
function a() { return new b();}a.prototype.method = function() { return this; }function b() {}b.prototype = a.prototype;
除了a
是jQuery
和b
是jQuery.prototype.init
。
我確定Resig有將他的api構造函數放在init原型中的原因,但是我看不到它們。除了Bergi提到的以外,還有其他一些奇怪之處:
1)圖案需要從參考副本jQuery.fn.init.prototype
到jQuery.prototype
,至極允許怪異無端環:
var $body = new $.fn.init.prototype.init.prototype.init.prototype.init('body');
2)每個jQuery集合實際上是的一個實例jQuery.fn.init
,但是由于它們引用相同的原型對象,因此欺騙我們“認為”該集合是的實例jQuery
。您可以執行以下相同的魔術:
function a(){}function b(){}a.prototype = b.prototype;console.log( new b instanceof a); // trueconsole.log( new a instanceof b); // true
旁注:我個人使用了以下構造函數模式,結果相似但沒有怪異:
var a = function(arg) { if (!(this instanceof a)) { return new a(arg); }};a.prototype.method = function(){ return this; };
添加回答
舉報