In JavaScript, a class getter is a special type of method within a class that allows you to define the retrieval behavior for a specific property. Getters are used to access the value of a property in an object in a controlled and encapsulated manner.
A class getter is defined using the get
keyword followed by the name of the getter method. When the getter method is accessed like a property, the code within the getter is executed, and its return value is returned.
In JavaScript, the syntax for defining a getter in a class is as follows:
class ClassName {
get propertyName() {
// Getter logic
return value;
}
}
- Start by declaring the class using the
class
keyword, followed by the class name (ClassName
in the example). - Define the getter method using the
get
keyword, followed by the name of the property you want to access (propertyName
in the example). The naming convention for getters is usually to use the same name as the property they retrieve. - Within the getter method block, you can include the logic to calculate or retrieve the value of the property. This could involve any necessary computations, accessing other class properties, or performing any other actions required to get the desired value.
- Finally, the getter should return the value that you want to be accessed when the property is accessed.
Here’s a concrete example that demonstrates the syntax:
class Circle {
constructor(radius) {
this._radius = radius;
}
get area() {
return Math.PI * Math.pow(this._radius, 2);
}
}
const circle = new Circle(5);
console.log(circle.area); // Output: 78.53981633974483
In the Circle
class, the getter method area
calculates and returns the area of the circle based on its radius.
JavaScript class getter example
Simple example code.
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
get fullName() {
return this._firstName + ' ' + this._lastName;
}
}
const person = new Person('John', 'Doe');
console.log(person.fullName); // Output: "John Doe"
In this example, we have a Person
class with a constructor that takes in a firstName
and lastName
. The class has a getter method called fullName
that concatenates the first name and last name, returning the full name of the person.
When we create an instance of the Person
class (person
), we can access the fullName
property using dot notation (person.fullName
). This automatically invokes the getter method, which combines the first and last names and returns the full name.
Note: the fullName
getter does not require parentheses when accessed, as it behaves like a property rather than a method.
Let’s consider a practical example of a JavaScript class with a getter.
class ShoppingCart {
constructor() {
this._items = [];
}
addItem(item) {
this._items.push(item);
}
get itemCount() {
return this._items.length;
}
get totalPrice() {
return this._items.reduce((total, item) => total + item.price, 0);
}
}
class Item {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const cart = new ShoppingCart();
cart.addItem(new Item('Shirt', 20));
cart.addItem(new Item('Pants', 30));
cart.addItem(new Item('Shoes', 50));
console.log(cart.itemCount);
console.log(cart.totalPrice);
Output:
In the example above, we have a ShoppingCart
class that keeps track of items added to the cart. The class has an array _items
to store the items. The addItem
method allows adding items to the cart.
The class also has two getter methods: itemCount
and totalPrice
. The itemCount
getter returns the number of items in the cart by accessing the length of the _items
array. The totalPrice
getter calculates the total price of all items in the cart using the reduce
method.
We create an instance of the ShoppingCart
class called cart
and add three Item
instances to it. We can then access the itemCount
and totalPrice
properties using the dot notation. The getter methods are automatically invoked, returning the calculated values.
In this practical example, the getters allow us to easily retrieve information about the items in the shopping cart, such as the total number of items and the total price.
Comment if you have any doubts or suggestions on this Js class topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version