I assume there is some application of call
or apply
here but I'm not sure how to implement it.
http://codepen.io/anon/pen/oXmmzo
a = {
foo: 'bar',
things: [1, 2, 3],
showFooForEach: function() {
this.things.map(function(thing) {
console.log(this.foo, thing);
});
}
}
a.showFooForEach();
Say I want to map
an array, but in the function, I need access to the this
to which foo
belongs. The function
of map
creates a new this
context, so I obviously need to coerse that context back in somehow, but how do I do that while still having access to thing
?
map allows a second argument called "thisArg" so you just use that like so:
Just realized I should have read the documentation for
Array.map()
more carefully. One simply needs to pass in thethis
value as the second parameter ofmap()
http://codepen.io/anon/pen/VLggpX
In addition, understanding how
bind()
,call()
andapply()
work are a must for serious JavaScript developers. These allow us to skip silly assignments likewith
There are three ways:
An plain-old variable
One that doesn't have the special oddness of
this
:Function.prototype.bind
Use the second parameter of Array.prototype.map
The (optional) second parameter is the context that the inner function is called with.
The first two ways are generic ways of dealing with
this
; the third is specific tomap
,filter
,forEach
.Nothing complex needed!
map
takes a second param ofthisArg
, so you just pass it in with the function you want to invoke on each item:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
As of 2018, you could use an arrow function:
You could use
bind()
it to your context.That's because of JS lexical scope
From MDN:
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
And here: http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
Also,
map()
does accept a second parameter as "this"From MDN
map()
documentation:Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Short advice