JS: this (binding)

By Xah Lee. Date: . Last updated: .

What is thisBinding

What is the Value of thisBinding?

Normal Usage

Abnormal Usage

When this is evaluated outside a function, its value is the Global Object.

Example. thisBinding in Method Call

The most common use is calling a function as a method of some object. e.g. a.b(). In such case, the value of this is the object that the method b is a property of. (the a)

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

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

Example. thisBinding in Constructor Call (new f())

When a function is invoked as a constructor (e.g. new F() or new obj.F()), its this value is the newly created object. (similar to this = Object.create(F.prototype))

〔see new (operator)

// typical example of using thisBinding
function F1(x) {
  this.kk = x;
}
const x = new F1(4);
console.log(x.hasOwnProperty("kk"));

Example. 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 F1() {
  return this;
}

console.log(F1() === undefined);
// in non-strict mode, in browser, thisBinding is the Global Object window

"use strict";

function F2() {
  return this;
}

console.log(F2() === window);

Example. 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.log(ff() === undefined);

// if in non strict mode, it returns the Global Object.

Call Function with Explicit Value of thisBinding

JavaScript. Constructor, Class