How do I get the right “this” in an Array.map?

Just realized I should have read the documentation for Array.map() more carefully. One simply needs to pass in the this value as the second parameter of map()

http://codepen.io/anon/pen/VLggpX

a = {
  foo: 'bar',
  things: [1, 2, 3],
  showFooForEach: function() {
    this.things.map(function(thing) {
      console.log(this.foo, thing);
    }, this);
  }
}
a.showFooForEach();

In addition, understanding how bind(), call() and apply() work are a must for serious JavaScript developers. These allow us to skip silly assignments like

var self = this;
myItems.map(function(item) {
  self.itemArray.push(item);
});

with

myItems.map(function(item) {
  this.itemArray.push(item);
}.bind(this));

Leave a Comment