Object Methods
JavaScript objects can have methods, similar to how classes behave in other languages. A method is simply a function that is defined as a property on an object.
Because objects serve multiple roles in JavaScript (acting as both dictionaries and the foundation for classes), methods are a highly common pattern for encapsulating logic alongside the data it manipulates.
Defining a Method
You define a method by creating a function directly inside the object.
const person = {
firstName: "Lane",
lastName: "Wagner",
// This is a method
getFullName() {
return this.firstName + " " + this.lastName;
},
};
console.log(person.getFullName());
// Output: "Lane Wagner"
The this Keyword
In the context of a standard object method, the this keyword refers to the object itself (similar to self in Python). By using this, the method can look inward and access or modify other properties belonging to the same object.
We will explore the complexities of this in more detail shortly.