Sub topic 1
How JavaScript Decides What this Is
In most languages with objects, this (or self) always refers to the object a method belongs to. JavaScript works differently. The value of this inside a function is set each time the function is called, and it depends on how the call is written. Where the function was defined and which object it was first attached to do not matter.
This chapter gives you the working model. Later chapters cover each rule in detail.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions and function expressions
- Objects, properties, and methods
- Basic scope and closures
- ES2015+ syntax, including arrow functions and classes
You should also be able to run snippets in Node.js or a browser console.
The Call Site Is What Counts
The call site is the place in your code where a function is invoked, the expression that ends in (...). To find this, ignore the function's definition and look at the call site.
Here, one function is called two different ways:
'use strict';
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
console.log(counter.increment()); // 1, this is counter
const inc = counter.increment;
try {
inc(); // same function, different call site
} catch (err) {
console.log(err instanceof TypeError); // true: this is undefined
}counter.increment and inc refer to the same function object. Copying it into inc does not change the function. The difference is the call. counter.increment() has an object before the dot, so this is counter. inc() is a plain call with nothing before it, so in strict mode this is undefined, and reading this.count throws.
The Four Ways to Call a Function
Every ordinary (non-arrow) function call fits one of four patterns. Each one sets this differently.
| Call pattern | Example | `this` is |
|---|---|---|
| `new` call | `new Box(1)` | A newly created object |
| Explicit call | `fn.call(obj)`, `fn.apply(obj)`, `fn.bind(obj)()` | The object you pass |
| Method call | `obj.fn()` | The object before the dot |
| Plain call | `fn()` | `undefined` in strict mode, `globalThis` in sloppy mode |
If more than one pattern seems to apply, the rows higher in the table usually win. The chapter on binding precedence covers the exact order and its edge cases.
Arrow functions are the exception to all four rows. An arrow function has no this of its own. It uses the this of the scope it was written in, and the call site cannot change that.
Common Errors This Model Explains
Most bugs involving this come from a function reaching a call site you did not expect:
- Extracting a method.
const f = obj.method; f();turns a method call into a plain call. - Passing a method as a callback.
setTimeout(obj.method, 100)passes only the function. The timer later calls it as a plain function, soobjis lost. - Assuming the definition decides. A method written inside an object literal is still an ordinary function. Writing it there does not tie
thisto that object.
In each case, ask one question: when this function actually runs, what does the call expression look like? If you can't see the call because a library or the runtime makes it, assume it is a plain call unless the documentation says otherwise.
Exercises
Exercise
Given const user = { name: 'Lin', hi() { return this; } }; in strict mode, what does each call return: (a) user.hi(), (b) const h = user.hi; h(), (c) const other = { hi: user.hi }; other.hi()?
Show answer
(a) user, because it is a method call on user. (b) undefined, because it is a plain call in strict mode. (c) other, because the object before the dot at the call site is other, even though the function was first defined on user.
Exercise
A strict-mode method obj.save is passed to setTimeout(obj.save, 0). Inside save, this is not obj. Using the call-site model, explain why.
Show answer
setTimeout receives only a reference to the function, not to obj. When the timer fires, it calls the function without any object before a dot, so it is a plain call and this is not obj. Fixes include setTimeout(() => obj.save(), 0) or setTimeout(obj.save.bind(obj), 0).