javascript / beginner
Snippet
Defining Encapsulated Data Models with JavaScript Classes
JavaScript classes provide an object-oriented pattern for modeling application entities with shared structure and behavior. Using a getter method (`get totalPrice`) creates computed properties that dynamically calculate values based on internal instance fields whenever accessed.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
class CartItem {constructor(title, unitPrice, quantity = 1) {this.title = title;this.unitPrice = unitPrice;this.quantity = quantity;}get totalPrice() {return this.unitPrice * this.quantity;}}
svelte
Breakdown
1
class CartItem {
Declares a class blueprint for representing individual items in a shopping cart.
2
constructor(title, unitPrice, quantity = 1) {
Defines the constructor method invoked upon instantiation to initialize instance properties.
3
this.title = title;
Assigns the item name to the newly created instance.
4
this.unitPrice = unitPrice;
Stores the single unit price on the instance.
5
this.quantity = quantity;
Sets the item count, using a default value of 1 if omitted.
6
}
Concludes the constructor definition.
7
get totalPrice() {
Defines a getter accessor that binds an object property to a function calculated dynamically on access.
8
return this.unitPrice * this.quantity;
Multiplies unit price by current quantity and returns the total cost.
9
}
Closes the getter method.
10
}
Closes the class body.