How is the this binding decided in JavaScript?
The this binding is decided by the way you call the function, and not by the place where you wrote it. There are four rules, and JavaScript always checks them in the same fixed order.
// 1. Default binding. A plain call with no receiver.
function plain() {
return this === globalThis;
}
console.log(plain()); // true in sloppy mode
// 2. Implicit binding. The object before the dot.
const obj = {
name: 'obj',
method() {
return this.name;
},
};
console.log(obj.method()); // 'obj'
// 3. Explicit binding. call, apply and bind.
console.log(obj.method.call({ name: 'other' })); // 'other'
// 4. The new binding. The object that was just created.
function Point(x) {
this.x = x;
}
console.log(new Point(3).x); // 3
// An arrow function keeps the this of the place where it was written.
const outerThis = this;
const arrow = () => this === outerThis;
console.log(arrow()); // true, the arrow kept the surrounding this
The order of the rules matters a great deal. If you call a function with the new keyword, then the new binding applies. If you do not use new but you used call, apply, or bind, then the explicit binding applies. If the call had an object in front of the dot, then the implicit binding applies. If none of those things happened, you get the default binding, which is the global object in sloppy mode and no value at all in strict mode.
The default binding is the rule that confuses people most, because it changes depending on the mode of the file. The same function called with no receiver gets the global object in sloppy code and nothing in strict code. That means code which relies on the default binding can work perfectly in one build and break in another one.
The arrow function line is the exception to the whole model. An arrow function has no binding of its own, so none of the four rules apply to it. It simply inherits the this of the scope where it was written, and it keeps that value forever.