JavaScript Object Methods
Object methods are functions that are stored as properties of objects. These methods allow you to perform actions or computations related to the object.
Defining Object Methods
You can define object methods by assigning functions as property values when creating the object or by adding methods to an existing object.
Example:
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
},
greet: function() {
console.log("Hello, " + this.firstName + "!");
}
};
console.log(person.fullName()); // Output: John Doe
person.greet(); // Output: Hello, John!
The “this” Keyword
The this
keyword refers to the current object and allows you to access its properties and methods within the object method.
Example:
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Output: John Doe
Using Object Methods
Object methods can be invoked using dot notation or bracket notation.
Example:
person.fullName(); // Output: John Doe
person["fullName"](); // Output: John Doe
The “bind” Method
The bind()
method allows you to create a new function that, when called, has its this
keyword set to a specific value.
Example:
const greetJohn = person.greet.bind(person);
greetJohn(); // Output: Hello, John!
Object methods are powerful tools for organizing and encapsulating functionality within JavaScript objects. They enable you to create reusable and modular code, improving the maintainability and readability of your applications.