Sub topic 1
How JavaScript Decides What this Is
Prerequisites
This chapter assumes you know how to write functions and function expressions and how objects and methods work. It also assumes you understand scope and closures and can read ES2015+ syntax.
The Call Site Rule
In most functions, this is not fixed when the function is written. JavaScript sets it each time the function runs, based on the call site, which is the expression that invokes the function. The same function can get a different this on every call. Arrow functions are the exception, and a later chapter covers them.
this at the Top Level and globalThis
Outside any function, this depends on how the code is loaded:
| Context | Top-level `this` |
|---|---|
| Classic browser script | `globalThis` (the `window` object) |
| ES module | `undefined` |
| Node.js CommonJS file | `module.exports` |
globalThis refers to the global object in every environment. Use it when you need the global object, and don't rely on top-level this.
Plain Function Calls: Sloppy vs Strict Mode
A bare call like fn() uses default binding. In sloppy mode, this becomes the global object. In strict mode, this stays undefined. Modules and class bodies are always strict.
function sloppy() {
return this;
}
function strict() {
'use strict';
return this;
}
// Run as a classic script, not a module:
console.log(sloppy() === globalThis); // true
console.log(strict()); // undefinedMethod Calls and the Object Before the Dot
When you call a function as a property of an object, this is the object before the dot. This is implicit binding.
'use strict';
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
console.log(counter.increment()); // 1, this is counter
const other = { count: 10, increment: counter.increment };
console.log(other.increment()); // 11, this is otherThe function belongs to no single object. Only the object in front of the dot at the moment of the call counts. In a.b.fn(), this is a.b.
Exercise
In a strict-mode script, const user = { name: 'Lin', hi() { return this; } }; const f = user.hi;. What do user.hi() and f() return?
Show answer
user.hi() returns user, because the call has user before the dot. f() returns undefined, because it is a plain call in strict code and default binding leaves this undefined.