After this lesson you can give your objects behaviour, not just data, and you can work out what this means in a given piece of code. this has a reputation for being confusing. It becomes simple once you remember one rule: look at how the function is called.
Methods
A method is a function that lives in an object property.
const counter = {
count: 0,
increment() {
this.count += 1;
},
describe() {
return `Count is ${this.count}`;
},
};
counter.increment();
counter.increment();
console.log(counter.describe()); // Count is 2The short syntax increment() { ... } is the same as increment: function () { ... }. Inside the method, this is the object the method was called on, here counter. That is how this.count reaches the count property.
The rule: how it is called
this is not fixed by where the function is written. It is set each time the function is called:
obj.method():thisisobj, the thing before the dot.method()on its own:thisisundefinedin strict mode (which includes modules and classes) and the global object in old sloppy code.method.call(x),method.apply(x)or a function made withbind(x):thisisx.new Thing():thisis the new object being built (see classes).
Here is the rule in action, including the failure case:
<pre id="out"></pre>
<script>
"use strict";
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const user = {
name: "Asha",
greet() {
return "Hi, I am " + this.name;
},
};
log(user.greet()); // called on user
const loose = user.greet; // pull the function out
try {
log(loose()); // called with nothing in front
} catch (error) {
log("Error:", error.constructor.name);
}
const fixed = user.greet.bind(user);
log(fixed()); // this is locked to user
</script>You will see Hi, I am Asha, then Error: TypeError (because this is undefined and reading .name from it fails), then Hi, I am Asha again. The function is the same each time; only the call changed.
Where this gets lost
The usual way to lose this is to hand a method over as a callback, which detaches it from its object:
const timer = {
label: "Tick",
start() {
setTimeout(this.show, 100); // this.show is passed alone: this is lost
},
show() {
console.log(this.label);
},
};Three fixes, all common:
setTimeout(this.show.bind(this), 100); // 1. bind
setTimeout(() => this.show(), 100); // 2. wrap in an arrow function
setTimeout(() => timer.show(), 100); // 3. call through the object nameThe second one is the most popular in modern code, and it leads to arrow functions.
Arrow functions and this
An arrow function does not have its own this. It uses the this of the code around it, decided where the arrow is written. That is ideal for a callback inside a method:
<pre id="out"></pre>
<script>
"use strict";
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const team = {
name: "Blue",
members: ["Asha", "Ben"],
list() {
// The arrow keeps this from list(), so this.name still works
return this.members.map(member => member + " is in " + this.name);
},
};
log(team.list().join("; "));
</script>The reverse also follows. Do not write an object's own methods as arrows: { count: 0, inc: () => { this.count++ } } fails, because the arrow takes this from outside the object literal, not from the object. Use method syntax for methods and arrows for the small functions inside them. More about arrows is in arrow functions.
call, apply and bind
You rarely need these, but you will read them in other people's code.
function introduce(greeting) {
return `${greeting}, ${this.name}`;
}
const person = { name: "Ben" };
console.log(introduce.call(person, "Hello")); // Hello, Ben
console.log(introduce.apply(person, ["Hi"])); // Hi, Ben
const bound = introduce.bind(person, "Hey");
console.log(bound()); // Hey, Bencall runs the function now with a chosen this and the arguments listed out. apply is the same with the arguments in an array. bind returns a new function for later.
Why this matters on the web
In a click handler written with a regular function, this is the element the listener is attached to, which you will see in the events lesson. An arrow function used there would not get that value. When in doubt, use event.currentTarget and skip the question.
Common mistakes
- Passing
obj.methodas a callback and losingthis. - Writing object methods as arrow functions, so
thisis not the object. - Thinking
thisis where the function is defined. It depends on the call. - Forgetting that
bindreturns a new function and does not call anything. - Using
thisin a plain function and expecting it to point to something useful. In strict code it isundefined.
Exercise
Create a wallet object with a balance of 100, a method spend(amount) that reduces the balance, and a method show() that returns a text like Balance: 70. Call them, then pull show into a separate variable and fix it with bind so it still works.
Show one possible answer
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const wallet = {
balance: 100,
spend(amount) {
this.balance -= amount;
},
show() {
return "Balance: " + this.balance;
},
};
wallet.spend(30);
log(wallet.show());
const show = wallet.show.bind(wallet);
log(show());
</script>Next: JSON.
Key points
- A method is a function stored as an object property, and you call it with a dot: obj.method().
- Inside a regular method, this is the object the method was called on.
- this is decided by how a function is called, not where it is written.
- Pulling a method out of its object loses this; bind, an arrow function wrapper or calling through the object fixes it.
- Arrow functions have no this of their own, so they are poor object methods but good for callbacks inside methods.