Lesson 55 of 296
How this is set
What you will learn
- What
thisis - The four rules that set
this, and their order - How arrow functions handle
this - How
thisgets "lost" thisin event listeners and classes
On this page
- What is this?
- Rule 1: method call (implicit binding)
- Rule 2: plain call (default binding)
- Rule 3: call, apply or bind (explicit binding)
- Rule 4: new (constructor call)
- Order of the rules
- Arrow functions: no own this
- Arrow functions as methods: the trap
- Losing this
- this in event listeners
- this in classes
- Quick decision guide
- Common mistakes
- How to say it in an interview
- Key words
What is this?
this is a special word inside a function. It refers to an object, and which object depends on how the function is called, not where it is written.
This is the opposite of normal variables, which use lexical scope (Lesson 50). That difference is why this confuses people.
Rule 1: method call (implicit binding)
When a function is called as a method, with a dot, this is the object before the dot.
const user = {
name: "Sam",
greet() {
return `Hi, I am ${this.name}`;
}
};
user.greet(); "Hi, I am Sam"The same function on another object gets a different this:
const other = { name: "Ali", greet: user.greet };
other.greet(); "Hi, I am Ali"Rule 2: plain call (default binding)
When a function is called on its own, with nothing before the dot:
function show() {
console.log(this);
}
show();- In strict mode (which includes all ES modules and classes):
thisisundefined. - In old non-strict scripts:
thisis the global object (windowin browsers).
Rule 3: call, apply or bind (explicit binding)
You can choose this yourself (Lesson 56):
function greet() {
return `Hi, ${this.name}`;
}
greet.call({ name: "Sam" }); "Hi, Sam"Rule 4: new (constructor call)
When a function is called with new, JavaScript creates a brand new empty object and sets this to it:
function User(name) {
this.name = name;
}
const u = new User("Sam");
u.name; "Sam"Order of the rules
When more than one could apply, this order wins:
new- Explicit:
bind/call/apply - Implicit: method call with a dot
- Default: plain call
Arrow functions: no own this
Arrow functions do not have their own this. They use the this of the code around them, where they were written (lexical this). The four rules above do not apply to them, and call, apply and bind cannot change it.
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; this is timer, from start()
}, 1000);
}
};
timer.start();With a normal function instead of the arrow, this inside the callback would be undefined (strict mode), because setInterval calls it as a plain function.
Arrow functions as methods: the trap
const user = {
name: "Sam",
greet: () => `Hi, ${this.name}`
};
user.greet(); "Hi, undefined"The arrow function takes this from outside the object (the module or global scope), not from user. Do not use arrow functions as object methods that need this.
Losing this
The most common this bug: taking a method off its object.
const user = {
name: "Sam",
greet() {
return `Hi, ${this.name}`;
}
};
const fn = user.greet;
fn(); TypeError: Cannot read properties of undefinedfn() is a plain call (rule 2), so this is undefined.
The same happens when you pass a method as a callback:
setTimeout(user.greet, 1000); loses this
button.addEventListener("click", user.greet); this becomes the buttonFixes:
setTimeout(() => user.greet(), 1000); call it as a method inside an arrow
setTimeout(user.greet.bind(user), 1000); bind this permanentlythis in event listeners
With a normal function, this is the element the listener is attached to:
button.addEventListener("click", function () {
this.classList.add("clicked"); this is the button
});With an arrow function, this is whatever it was outside. Use event.currentTarget instead; it always works:
button.addEventListener("click", (event) => {
event.currentTarget.classList.add("clicked");
});this in classes
Inside class methods, this is the instance (the object made with new). But methods still lose this when passed as callbacks. A common fix is an arrow function class field:
class Clock {
seconds = 0;
tick = () => {
this.seconds++;
};
}
const c = new Clock();
setInterval(c.tick, 1000); works: tick always uses this instanceQuick decision guide
To find this, look at how the function is called:
- Is it an arrow function? Use the
thisfrom where it was written. - Called with
new? The new object. - Called with
call,apply, or is it a bound function? The object given. - Called as
something.fn()?something. - Otherwise:
undefinedin strict mode.
Common mistakes
- Arrow functions as object methods.
- Passing
obj.methodas a callback and losingthis. - Expecting
thisto follow lexical scope like variables.
How to say it in an interview
"this is decided by how a function is called. With new it is the new object; with call, apply or bind it is the object passed; as a method call it is the object before the dot; and as a plain call it is undefined in strict mode. Arrow functions do not have their own this and take it lexically from the surrounding scope, which makes them good for callbacks but bad as object methods. The most common bug is passing a method as a callback, which loses this; I fix it with bind or a wrapping arrow function."
Key words
| Word | Meaning |
|---|---|
| this | A reference set by how a function is called |
| Implicit binding | this is the object before the dot |
| Default binding | Plain call: undefined in strict mode |
| Explicit binding | Setting this with call, apply or bind |
| new binding | this is a newly created object |
| Lexical this | Arrow functions using the this of the surrounding code |
| Strict mode | A safer mode of JavaScript, on by default in modules and classes |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.