Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda 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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 5

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Awesome!

Completion rate improved to 6.25

bookGetters in Classes

Deslize para mostrar o 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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 5
some-alt