如何在Lo-Dash中使用thisArg?

时间:2014-03-25 03:55:32

标签: javascript lodash

如何在Lo-Dash中使用thisArg?是否可以将其与链接相结合?这是一个在文档中使用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.

我将不胜感激,因为我无法在他们的文档中找到任何内容。

1 个答案:

答案 0 :(得分:4)

参数thisArg只是指向调用者的this上下文的指针,它也将用作回调的上下文。它是为了方便而提供的。

结果与使用原生Function.bind()方法相同,例如:

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

另一种方法是创建this的别名变量并改为使用它。