JS: this (binding)

By Xah Lee. Date: . Last updated: .

What is thisBinding

In JavaScript, when a function is called, it has a magic value called thisBinding. (Except Arrow Function.)

In function body, the thisBinding is represented by the keyword this.

The purpose of thisBinding is to allow function to implicitly work with a object without actually passing it as argument.

For example, in xArray.reverse(), the function reverse's thisBinding have the value of xArray, due to just JavaScript design. That's how reverse knows about xArray. (xArray knows about reverse because it is a property.)

A function may or may not make use of thisBinding. If a user defined function body does not contain this keyword, then the associated thisBinding does nothing.

What is the Value of thisBinding?

thisBinding in Method Call

When a function f is called by property access, e.g. obj.f(), the value of this is obj.

let jj = {
 ff: function () {
  return this;
 },
};

console.assert(jj === jj.ff());

thisBinding in Constructor Call (new f())

When a function f is called with the keyword new, as in new f() or new obj.f(), the value of this is the newly created object. (similar to this = Object.create(F.prototype))

// typical example of using thisBinding
function Xcon(x) {
 this.kk = x;
}
const x = new Xcon(4);
console.assert(Object.hasOwn(x, "kk"));

Abnormal Usage

thisBinding in Global Function Call

When a function is called in a global context and not as a method of another object, the this evaluates to undefined if Strict Mode is on, else it's the Global Object .

"use strict";

function Xcon() {
 return this;
}

console.assert(Xcon() === undefined);

thisBinding in Nested Functions

In a nested function (e.g. g is nested inside f), when g is called inside f, the value of g's this is undefined if Strict Mode is on, else the Global Object .

// thisBinding is in nested function has value undefined, if under use strict

"use strict";

function ff() {
 const gg = function () {
  return this;
 };
 return gg();
}

console.assert(ff() === undefined);

Call Function with Explicit Value of thisBinding

JavaScript. Constructor, Class