The other day I was hanging out at #javascript and noticed not many were aware of thisArg
that few of the built-ins have in their signature.
Basically if a thisArg
parameter is provided, it will be used as the this value for each invocation of callbackfn
or predicate
.If it is not provided, undefined is used instead.
It's improtant to note that if callbackfn
is an (Fat) Arrow Function, this was lexically bound when the function was created so thisArg
will have no effect.
Ofcourse there are apply
, bind
and call
which could be used to change the execution context taken in thisArg
, below is the list of few more built-ins that have thisArg
in their signature:
Array.from ( arrayLike [ , mapfn [ , thisArg ] ] )
Array.prototype.every ( callbackfn [ , thisArg] )
Array.prototype.filter ( callbackfn [ , thisArg ] )
Array.prototype.find ( predicate [ , thisArg ] )
Array.prototype.findIndex ( predicate [ , thisArg ] )
Array.prototype.forEach ( callbackfn [ , thisArg ] )
Array.prototype.map ( callbackfn [ , thisArg ] )
Array.prototype.some ( callbackfn [ , thisArg ] )
Let us see an example of forEach
:
1 2 3 4 5 |
|
Without thisArg
:
1 2 3 4 5 |
|
With thisArg
:
1 2 3 4 5 6 7 |
|
The same could be achived with bind
, but it would be slower.
1 2 3 4 5 6 7 |
|
Have a looks at the perf values.
All of them results in the same output, it's advised to use thisArg
whenever possible.
UPDATE: Here a video from webucator explaining the same.