2014-03-25 55 views
3

如何在Lo-Dash中使用thisArg?有沒有可能將它與鏈接結合起來?這是一個使用thisArg從他們的文檔的例子:如何在Lo-Dash中使用thisArg?

_.map(collection, [callback=identity], [thisArg]) 

Creates an array of values by running each element in the collection through the callback. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection). 

If a property name is provided for callback the created "_.pluck" style callback will return the property value of the given element. 

If an object is provided for callback the created "_.where" style callback will return true for elements that have the properties of the given object, else false. 

Aliases 

_.collect 

Arguments 

collection (Array|Object|string): The collection to iterate over. 
[callback=identity] (Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively. 
[thisArg] (*): The this binding of callback. 
Returns 

(Array): Returns a new array of the results of each callback execution. 

一個例子,將不勝感激,因爲我無法找到任何自己的文檔。

回答

3

參數thisArg只是指向this指向調用方的上下文,該上下文也將用作回調的上下文。它提供了方便。

結果是一樣的,如果使用本機Function.bind()方法例如爲:

_.map(collection, callback.bind(this)); 

另一種方法將是使的this別名變量,並用它來代替。

+0

是否有可能使用這個參數有一個變量'this'綁定?例如。 'O = {foo:function(){return this.bar; },bar:42}; A = [O,O]; _.map(A,O.foo,_.identity)'? (最後一個表達式不能按預期工作) –

+0

我直接在github上打開了一個問題:https://github.com/lodash/lodash/issues/803 –