2 回答

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

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