When Budi says "I'm hungry", "I" means Budi. When Ani says the same sentence, "I" means Ani. The sentence is exactly the same. Only the speaker changes.
this in JavaScript works like the word "I". this is a keyword used inside a function, and it points to one object. The function is like the sentence, and the object that calls the function is like the speaker. So which object this points to is not decided when the function is written, but when the function is called.
this inside a method
The object below has one method that uses this:
const user = {
name: "Budi",
greet() {
return "Hi " + this.name;
},
};
console.log(user.greet()); // Hi Budi
useris an object with anameproperty and agreetmethod.- Inside
greet,thispoints to the object left of the dot when the method is called.user.greet()meansthisisuser, sothis.nameis"Budi". - Through
this, a method can read and change the properties of its own object, for examplethis.name = "Ani".
The rule: look at how the function is called, not where the function was written. The object left of the dot is this.
A method taken away from its object
Here the greet method is copied into an ordinary variable, then called with no object in front of it:
const greet = user.greet;
console.log(greet());
// strict mode: TypeError, because this is undefined
// without strict mode: "Hi ", because this is window
greet() is called with no object left of the dot, so this is no longer user. Strict mode is a stricter set of JavaScript rules (switched on automatically in modules and classes, which come later). The result depends on it:
- In strict mode,
thisisundefined, andthis.namecauses an error. - Without strict mode,
thisis the global objectwindow(an object built into the browser). Thenameproperty ofwindowis empty, so the result is wrong and no error tells you.
So a method taken away like this can't greet Budi any more. This often happens when a method is passed as a callback (a function you give to another function). An example is setTimeout(user.greet, 1000), which runs that function 1 second later: only the function is passed, without user.
Choose this yourself: call, apply, bind
Every function has three built-in methods that let you choose the object that becomes this:
const admin = { name: "Ani" };
console.log(user.greet.call(admin)); // Hi Ani
const greetBudi = user.greet.bind(user);
console.log(greetBudi()); // Hi Budi
call(obj, arg1, arg2)calls the function right away, withthis=obj.arg1andarg2become that function's arguments. In the example,thisisadmin, so the result is Hi Ani.apply(obj, [arg1, arg2])is the same ascall. There is one difference: the arguments are passed as one array.bind(obj)does not call the function.bindmakes a new function whosethisis locked toobj, so that new function is safe to pass anywhere.
Arrow functions have no this of their own
In the object below, the method is written as an arrow function:
const cat = {
name: "Oyen",
sound: () => this.name,
};
console.log(cat.sound()); // undefined
An arrow function does not look at the object left of the dot. It uses the this of its outer scope, which is the code around the place where the arrow function was written. An object's curly brackets are not a scope, so the outer scope is the code outside cat. There, this is not cat, so the result is undefined. That is why you write methods as normal functions: sound() { ... }.
This same behaviour is useful for callbacks inside a method. Below, an arrow function is written inside the start method. That arrow function uses the this of start, which is timer:
const timer = {
seconds: 3,
start() {
setTimeout(() => console.log(this.seconds), 1000); // 3
},
};
timer.start();
Return this so calls can be chained
A method can also return this, which is its own object:
const steps = {
count: 0,
forward() {
this.count += 1;
return this;
},
show() {
return this.count;
},
};
console.log(steps.forward().forward().show()); // 2
forward()adds one tothis.count, thenreturn thisreturns thestepsobject itself.- The result of
steps.forward()isstepsagain. So you can write the next method right after it. This is called chaining. - Without
return this,steps.forward()givesundefined, and the second.forward()causes an error.
⚠️ When this doesn't point to your object
- An arrow function as a method. In
sound: () => this.name,thisis not the method's object. Writesound() { ... }. - Forgetting
this.count += 1inside a method looks for a variable calledcount, not the object's property. Writethis.count += 1. - Passing a method on as a callback.
setTimeout(user.greet, 1000)takes the method away from its object, so itsthisis lost. UsesetTimeout(() => user.greet(), 1000)oruser.greet.bind(user).
TL;DR: The value of this is decided by how a function is called: obj.method() means this is obj, the object left of the dot. A method that is copied into a variable and called with no object left of the dot loses its this. call and apply call a function with the this you choose, while bind makes a new function with this locked. Arrow functions have no this of their own and use the this of the outer scope (the code around them), so don't use them for methods. Methods that run return this can be chained: obj.a().b().
⚡ this is the object left of the dot
Write:
const user = {
name: "Budi",
greet() {
return "Hi " + this.name;
},
};
console.log(user.greet()); // Hi Budi
Meaning: this is a keyword used inside a function, and it points to one object. That object is decided when the function is called, not when it is written. user.greet() means this is user, the object left of the dot, so this.name is "Budi".
⚡ A method taken away loses its this
Write:
const greet = user.greet;
greet();
const greetBudi = user.greet.bind(user);
greetBudi(); // Hi Budi
Guess first: does greet() still greet Budi?
No. There is no object left of the dot, so this is no longer user. In strict mode (a stricter set of JavaScript rules), this call even causes a TypeError.
Meaning: A method that is copied into a variable and called with no object left of the dot loses its this. This often happens when a method is passed as a callback (a function you give to another function). bind(user) makes a new function whose this is locked to user.
⚡ An arrow function uses the outer this
Write:
const cat = {
name: "Oyen",
sound: () => this.name,
};
Guess first: what does cat.sound() give?
undefined. An arrow function has no this of its own, so it uses the this of its outer scope: the code around the place where the arrow function was written. There, this is not cat.
Meaning: Write methods as normal functions: sound() { ... }. Arrow functions are the right choice for callbacks inside a method, because an arrow function uses that method's this.