Skip to content

tsukiy0's blog

`this` context in JavaScript

March 09, 2018

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. This is the most consistent approach and thus preferred.

const foo = a => {
this.a = a;
};
const bar = {
foo: foo
};
bar.foo(2);
console.log(bar.a); // undefined
console.log(this.a); // 2

tsukiy0