JavaScriptHard
What is the 'this' keyword?
this is a value set when a function is called (not where it is defined), and it refers to the object the function is acting on; arrow functions are the exception, taking this from the surrounding scope.
The rules, in priority order
newbinding:new Fn()setsthisto the newly created object.- Explicit binding:
fn.call(obj),fn.apply(obj)orfn.bind(obj)setthistoobj. - Implicit binding:
obj.method()setsthistoobj(whatever is left of the dot at call time). - Default binding: a plain call
fn()givesundefinedin strict mode (and in modules and classes), or the global object in sloppy mode.
Arrow functions ignore all of these and use this from where they were written.
Losing this
The most common bug: passing a method as a callback (setTimeout(obj.method) or onClick={this.handle}) detaches it from the object, so the call becomes a plain call and this is undefined. Fixes: bind, an arrow wrapper, or class field arrow methods.
Other contexts
- In a class body and ES modules, code runs in strict mode.
- In DOM event handlers written as normal functions,
thisis the element the listener is attached to (event.currentTarget). - At the top level of a module
thisisundefined; in a classic browser script it iswindow.
Code example
js
1"use strict";23const user = {4 name: "Ada",5 greet() {6 return `Hi, I am ${this?.name}`;7 },8};910console.log(user.greet()); // implicit: Hi, I am Ada1112const detached = user.greet;13console.log(detached()); // default (strict): Hi, I am undefined1415console.log(detached.call({ name: "Linus" })); // explicit: Hi, I am Linus16const bound = user.greet.bind(user);17console.log(bound()); // bound: Hi, I am Ada1819function Person(name) {20 this.name = name; // `new` binding: this = new object21}22console.log(new Person("Grace").name); // Grace2324class Clock {25 ticks = 0;26 tick = () => ++this.ticks; // arrow class field: always this instance27}28const clock = new Clock();29const fn = clock.tick; // safe to pass around30fn();31fn();32console.log(clock.ticks); // 2
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.