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"
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain how setters work in a similar way?
What are some common use cases for getters in JavaScript classes?
Can you show how to add validation when setting the price?
Awesome!
Completion rate improved to 6.25
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"
Дякуємо за ваш відгук!