Methods and this
An object can store not only data but also actions on that data. A function stored in an object property is called a method. Methods keep the data and the code that works with it in one place.
An object method
A method is an ordinary function written as a property value. It is called with a dot and parentheses:
const user = {
name: 'Anna',
greet: function () {
return 'Hello!';
},
};
console.log(user.greet()); // Hello!Shorthand method syntax
The : function part can be left out — this is how methods are written in modern code:
const calculator = {
add(a, b) {
return a + b;
},
};
console.log(calculator.add(2, 3)); // 5this
Inside a method, the this keyword means the object the method was called on. Through it the method reads and changes the properties of its object:
const user = {
name: 'Anna',
greet() {
return `Hello, I am ${this.name}`;
},
};
console.log(user.greet()); // Hello, I am AnnaThe value of this is decided at the moment of the call: in user.greet() it is the object to the left of the dot.
Methods that change the object
A method can modify the object's properties. Counters, carts and other objects with state — data that changes over time — work this way:
const counter = {
value: 0,
increment() {
this.value++;
},
};
counter.increment();
counter.increment();
console.log(counter.value); // 2Shorthand properties
If a property name matches a variable name, it is enough to write it once. This is common when an object is assembled from existing variables:
const name = 'Oleg';
const age = 30;
const user = { name, age };
console.log(user.age); // 30{ name, age } means the same as { name: name, age: age }.
Common mistake
An arrow function has no this of its own, so it is not used for methods. Also, this is lost when a method is taken away from its object and called on its own:
const user = {
name: 'Anna',
greet() {
return `Hello, I am ${this.name}`;
},
};
const greet = user.greet; // the method is copied without the object
greet(); // this no longer points to userThis happens when a method is passed to another function, for example setTimeout(user.greet, 1000). The fix is to pass an arrow function that calls the method on the object: setTimeout(() => user.greet(), 1000).