1. saving function in object
In JavaScript, functions can be stored as properties in an object, which is a powerful feature that allows for more dynamic behavior within objects. When a function is stored in an object, it is referred to as a method. Methods allow objects to perform actions related to their data.
2. Example: Saving a Function in an Object
Here's a simple example of storing a function inside an object and calling it:
const person = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
console.log(person.fullName()); // Output: "John Doe"
Breakdown of the Example:
person
is an object with properties firstName
, lastName
, and fullName
.fullName
is a function stored inside the person
object. It can access other properties of the object (firstName
, lastName
) using the this
keyword.person.fullName()
, the method is executed and returns the full name by combining firstName
and lastName
.
Storing Multiple Functions
You can store multiple functions (methods) in an object to allow for various actions:
const calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
multiply: function(a, b) {
return a * b;
},
divide: function(a, b) {
return a / b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.subtract(10, 4)); // Output: 6
console.log(calculator.multiply(6, 7)); // Output: 42
console.log(calculator.divide(20, 5)); // Output: 4
Key Points:
this
keyword is used to access other properties of the object.
Advanced Example: Using Functions to Modify Object Properties
In this example, the object has methods to update and display its properties dynamically:
const car = {
brand: 'Toyota',
model: 'Corolla',
year: 2020,
displayInfo: function() {
return `${this.brand} ${this.model} (${this.year})`;
},
updateYear: function(newYear) {
this.year = newYear;
}
};
console.log(car.displayInfo()); // Output: "Toyota Corolla (2020)"
car.updateYear(2022);
console.log(car.displayInfo()); // Output: "Toyota Corolla (2022)"
Here, the updateYear function allows updating the year property of the car object, and the displayInfo method returns the updated information.
Conclusion
In JavaScript, saving functions inside objects as methods provides a powerful way to encapsulate behavior along with data. This makes your code more organized, reusable, and modular. Methods can access the object's properties using the this keyword, allowing dynamic behavior based on the object’s state. Whether you’re working with simple objects like a person or more complex ones like a calculator or car, storing functions within objects helps streamline how you manage and interact with data.