2013-10-15 63 views
4

我很好奇,_.chain ing function is implemented以及它如何(或更好,爲什麼)按照它的方式工作。下劃線鏈接內部工作

特別是我的問題是每個功能的包裝發生在哪裏。假設我使用_.chain(someArray).filter(...);當我步入功能,我可以看到,過濾功能得到了改造成類似

function() { 
    var args = [this._wrapped]; //the data from chain(...) 
    push.apply(args, arguments); //push to the (?) array 
    return result.call(this, func.apply(_, args)); //?? where are these coming from? 
} 

我可以看到該函數有3個閉包在它的範圍(比較這對un-chained function,展示了函數的定義,而不全部關閉,以它的原始功能)

scope after using the chain function

第一個是find function本身,第二"the safe reference to the object itself"和下劃線類本身的三分之一。

當調用_.chain()時,如何和在哪裏(代碼方式)進行轉換(創建範圍等)。我可以看到

//http://underscorejs.org/docs/underscore.html#section-139 
_.chain = function(obj) { 
    return _(obj).chain(); 
    }; 

被調用,這去

//http://underscorejs.org/docs/underscore.html#section-145 
//... 
chain: function() { 
     this._chain = true; 
     return this; 
    }, 
//... 

然後我卡。我無法弄清楚那裏會發生什麼。我認爲魔術發生在constructor內部,但我似乎無法弄清楚閉包的附加創建在哪裏進來。所有功能本身都沒有顯示任何纏繞的跡象,連鎖調用看起來沒有像它包裝的東西。 result似乎在那裏,但我不知道它來自哪裏。那麼,在哪裏以及如何發生?

+0

http://underscorejs.org/docs/underscore.html#section-143最後,您可以看到所有原型方法的添加位置 – Zirak

回答

0

_.chain(obj)返回_新實例屬性_chain = true_該實例有一個_wrapped屬性設置爲當前對象(這裏是偉大的工作)。 _.mixin(_)#1210添加下劃線方法的所有下劃線(構造函數)。 _.mixin方法替換和擴展_方法(仍然有父功能!可通過_.prototype訪問)。 _.mixin更改_實例的功能(這是您看到新功能的地方)。

新功能:

function() { 
    var args = [this._wrapped]; 
    push.apply(args, arguments); 
    return result.call(this, func.apply(_, args)); 
} 

(無所謂,func被引用到原來的方法什麼方法是,同樣爲所有)

result方法的功能是:

var result = function(obj) { 
    return this._chain ? _(obj).chain() : obj; 
}; 

所以如果func.apply(_, args)返回的對象有_chain_.chain設置屬性)返回_(obj).chain()然後你可以再次使用它:)

這是鏈接的過程,但原型怎麼樣!

在構造函數:

var _ = function(obj) { 
    if (obj instanceof _) return obj; 
    if (!(this instanceof _)) return new _(obj); // This line do the magic 
    this._wrapped = obj; 
}; 

考慮一下:

func = function(a){this.a = a;} 
b = func(2); 
b.a // TypeError: Cannot read property 'a' of undefined 
c = new func(2); 
c.a // returns 2, whooa this the magical javascript! 

閱讀(Underscore docs about OOP)如果您想了解更多有關下劃線的mixin功能

我缺少的東西?