Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

thisArg in Javascript

| Comments

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
let jedi = {
  name: 'yoda',
  height: '66cms',
  mass: '17 kgs'
};

Without thisArg:

1
2
3
4
5
Object.keys( jedi ).forEach(function( key ) {

  console.log( jedi[ key ] );

});

With thisArg:

1
2
3
4
5
6
7
Object.keys( jedi ).forEach(function( key ) {

  // |this| now refers to `jedi`

  console.log( this[ key ] );

}, jedi ); // last arg is `thisArg`

The same could be achived with bind, but it would be slower.

1
2
3
4
5
6
7
Object.keys( jedi ).forEach(function( key ) {

  // |this| now refers to `jedi`

  console.log( this[ key ] );

}.bind(jedi) ); // We are binding the execution context.

Have a looks at the perf values.

All of them results in the same output, it's advised to use thisArgwhenever possible.

UPDATE: Here a video from webucator explaining the same.

Comments