Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Getters in Classes | Inheritance and Encapsulation
JavaScript Classes and OOP Foundations

bookGetters 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.

12345678910111213
class 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"
copy
question mark

Which statement best describes how getters work in JavaScript classes and their main benefit

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 5

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Suggested prompts:

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

bookGetters in Classes

Scorri per mostrare il menu

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.

12345678910111213
class 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"
copy
question mark

Which statement best describes how getters work in JavaScript classes and their main benefit

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 5
some-alt