JS: this-binding
What is this-binding
In JavaScript, when a function is called, it has a magic value called this-binding. (Except Arrow Function.)
In function body, the this-binding is represented by the keyword this.
The purpose of this-binding is to allow function to implicitly work with a object without actually passing it as argument.
A function may or may not make use of this-binding. If a user defined function body does not contain this keyword, then the associated this-binding does nothing.
What is the value of this-binding?
this-binding 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());
this-binding 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 this-binding function Xcon(x) { this.kk = x; } const x = new Xcon(4); console.assert(Object.hasOwn(x, "kk"));
Abnormal usage
this-binding 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);
this-binding 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
.
// this-binding 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);