How to use methods and this
Add a method
A method is a function stored on an object. In a normal method call, this refers to the object before the dot.
const counter = {
value: 0,
increment() {
this.value += 1;
return this.value;
}
};
console.log(counter.increment());
Understand the call site
Extracting a method loses its receiver, so this is no longer the original object. Modules and strict mode make such mistakes easier to notice.
"use strict";
const user = {
name: "Nia",
introduce() { return `I am ${this.name}`; }
};
console.log(user.introduce());
// const speak = user.introduce;
// speak(); // this is undefined
Bind a receiver when needed
bind creates a function whose this is fixed. This is useful when passing a method as a callback.
const timer = {
label: "Study",
show() { console.log(this.label); }
};
const showTimer = timer.show.bind(timer);
showTimer();
Know arrow function behavior
Arrows capture this from their surrounding scope, so they are usually unsuitable as object methods that need the receiver.
const team = {
name: "Blue",
members: ["Ana", "Bo"],
labels() {
return this.members.map(member => `${this.name}: ${member}`);
}
};
console.log(team.labels());