Getters in Classes
When you want to control how a property is accessed in a class, you can use a getter method. Getters allow you to define special methods that are accessed like properties, using the get keyword. This lets you compute a value, validate data, or even hide internal implementation details, all while letting users of your class interact with the property as if it were a regular field. With getters, you can make your classes safer and more flexible by controlling what happens when someone tries to read a property.
12345678910111213class Product { constructor(name, priceCents) { this.name = name; this._priceCents = priceCents; } get price() { return (this._priceCents / 100).toFixed(2); } } const item = new Product("Headphones", 2599); console.log(item.price); // "25.99"
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 6.25
Getters in Classes
Svep för att visa menyn
When you want to control how a property is accessed in a class, you can use a getter method. Getters allow you to define special methods that are accessed like properties, using the get keyword. This lets you compute a value, validate data, or even hide internal implementation details, all while letting users of your class interact with the property as if it were a regular field. With getters, you can make your classes safer and more flexible by controlling what happens when someone tries to read a property.
12345678910111213class Product { constructor(name, priceCents) { this.name = name; this._priceCents = priceCents; } get price() { return (this._priceCents / 100).toFixed(2); } } const item = new Product("Headphones", 2599); console.log(item.price); // "25.99"
Tack för dina kommentarer!