How to Create and Call Object Methods in JavaScript
In JavaScript, a function that is a property of an object is called a method. Creating methods is a fundamental part of object-oriented programming, allowing you to bundle data (properties) and the behavior that acts on that data (methods) together into a single, organized unit.
This guide will teach you the modern, standard syntax for creating and calling object methods. You will learn how to use the this keyword to access other properties of the object and, most importantly, understand the critical pitfall of using arrow functions as methods.
The Core Method: Defining and Calling Methods
In modern JavaScript (ES6+), there is a concise and readable syntax for defining methods directly within an object literal.
For example, we want to create an object that has a function attached to it.
The recommended solution is to define the method directly with the name, parentheses, and curly braces.
const calculator = {
// This is the modern method syntax
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
};
// You can call the methods using dot notation
console.log(calculator.add(10, 5)); // Output: 15
console.log(calculator.subtract(10, 5)); // Output: 5
This is a shorthand for the older function expression syntax (add: function(a, b) { ... }), and it is the recommended best practice in modern JavaScript.
How to Use the this Keyword to Access Object Properties
The real power of methods comes from their ability to interact with the data stored on the same object. The this keyword is the key to this interaction. Inside a method defined with a regular function, this refers to the object the method was called on.
For example, we have an object with data and we want a method that can use that data.
// Problem: How can the `greet` method access the `name` property?
const user = {
name: 'Alice',
id: 123,
};
Solution:
const user = {
name: 'Alice',
id: 123,
// This method uses `this` to access other properties on the `user` object.
greet() {
return `Hello, my name is ${this.name}.`;
},
getId() {
return `My ID is ${this.id}.`;
}
};
console.log(user.greet()); // Output: "Hello, my name is Alice."
console.log(user.getId()); // Output: "My ID is 123."
The Critical Pitfall: Arrow Functions and this
This is one of the most common sources of bugs for developers. You cannot use an arrow function for an object method if you need to access this.
Why? Arrow functions do not have their own this binding. They lexically inherit this from their surrounding scope. In the case of an object literal, the surrounding scope is typically the global scope (where this is window in a browser, or undefined in a module).
Example of code with problems:
const user = {
name: 'Alice',
id: 123,
// ⛔️ This will NOT work as expected!
greet: () => {
// `this` here does not refer to the `user` object.
console.log(this); // Output: window (in a browser) or undefined
return `Hello, my name is ${this.name}.`;
},
};
console.log(user.greet()); // Output: "Hello, my name is undefined."
Because this does not refer to the user object, this.name is undefined, and the method fails.
The Solution is to always use regular functions or the method syntax for object methods that need to access this. Never use arrow functions for this purpose.
Conclusion
Creating and calling methods is a fundamental concept in JavaScript.
- Use the concise method syntax (
myMethod() { ... }) to define functions on objects. - Use the
thiskeyword inside your methods to access other properties on the same object. - Never use an arrow function to define a method if that method needs to use the
thiskeyword, as it will not be bound to the object.
By following these simple rules, you can write clean, effective, and object-oriented code.