`this` context

  • #javascript

Types

Default

By default, this is bound to the global context.

function foo(a) {
  this.a = a;
}

foo(2);

console.log(this.a); // 2

Constructor

Constructor functions, that is functions called with new keyword, have this bound to the new object being constructed.

function Foo(a) {
  this.a = a;
}

const bar = new Foo(2);

console.log(bar.a); // 2

Implicit

When a function is called as a method of an object, its this is bound to that object.

function foo(a) {
  this.a = a;
}

const bar = {
    foo: foo
};


bar.foo(2);

console.log(bar.a); // 2
const baz = bar.foo;

baz(4);

console.log(bar.a); // 2
console.log(this.a); // 4

Explicit

A function can be explicitly bound to a context using bind.

function foo(a) {
  this.a = a;
}

const bar = {};

const boundFoo = foo.bind(bar);
boundFoo(2);

console.log(bar.a); // 2

Arrow Syntax

this is bound to the context where the arrow function was defined.

const foo = a => {
  this.a = a;
};

const bar = {};

bar.foo = foo;

bar.foo(2);

console.log(bar.a); // undefined
console.log(this.a); // 2

Tips

  • Always use arrow syntax to define functions.
  • Use explicit binding when necessary.
  • Sometimes a 3rd party library leverages implicit binding. To avoid confusion, it is beneficial to encapsulate these instances within your own functions.