Binding contexts

You might not always want to use anonymous functions, or Lo-Dash functions, as your map() callback. This is the same case with reduce(). Luckily, you can easily bind the callback function context in both cases. For example, let's say that you have an application object that is not global. You can still make it the context of your callback function, as shown in the following code:

var app = { states: [ 'running', 'off', 'paused' ], machines: [ { id: _.uniqueId(), state: 1 }, { id: _.uniqueId(), state: 0 }, { id: _.uniqueId(), state: 0 }, { id: _.uniqueId(), state: 2 } ] }; var mapStates = _.partialRight(_.map, function(item) { return _.extend({ state: this.states[item.state] }, _.pick(item, 'id')); }, app); mapStates(app.machines); ...

Get Lo-Dash Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.