Javascript getters
Created By: chatGPT
Getters are a special type of method in JavaScript that allow you to define a property on an object. When you access this property, the getter is invoked. This is useful for transforming data and providing a controlled way to retrieve data from an object. You define a getter using the
get
keyword followed by a method name. It's often used in conjunction with object literals or class definitions.const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName); // Output: John Doe
You can also define getters in a class. When using getters, you can encapsulate the logic that returns the desired value, which leads to cleaner and more maintainable code. Here’s how you can implement a getter inside a class.
class Circle {
constructor(radius) {
this._radius = radius;
}
get area() {
return Math.PI * this._radius * this._radius;
}
}
const myCircle = new Circle(5);
console.log(myCircle.area); // Output: 78.53981633974483
One of the advantages of using getters is that they can be used to calculate properties on the fly. For instance, if you want to compute the total price of items in a cart based on their quantities and prices, you can define a getter that calculates this when it is accessed.
In conclusion, getters provide an elegant way to access properties in JavaScript. They help encapsulate logic within an object, making your code cleaner and more intuitive. However, keep in mind that using getters can have a performance impact as they are executed each time the property is accessed.class ShoppingCart {
constructor() {
this.items = [];
}
get totalPrice() {
return this.items.reduce((total, item) => total + item.price * item.quantity, 0);
}
}
const cart = new ShoppingCart();
cart.items.push({ price: 10, quantity: 2 });
cart.items.push({ price: 5, quantity: 3 });
console.log(cart.totalPrice); // Output: 35