⊗jsOpBsPG 16 of 60 menu

Property Getters in OOP in JavaScript

Let's say we have the following class with private properties:

class User { #name; #surn; constructor(name, surn) { this.#name = name; this.#surn = surn; } }

As you can see, these properties are set once when the object is created. However, these properties cannot be read now, because they are private and there are no corresponding methods for this.

Let's make special methods for our properties that allow us to read these properties. Such methods (they are called getters) should begin with the word get, and then the name of the property to read should follow.

Let's make getters for our properties:

class User { #name; #surn; constructor(name, surn) { this.#name = name; this.#surn = surn; } getName() { return this.#name; } getSurn() { return this.#surn; } }

Let's check their work. Let's create an object, passing user data as a parameter:

let user = new User('john', 'smit');

Let's read this data using getters:

console.log(user.getName()); console.log(user.getSurn());

In the Employee class, make three private properties: name, salary, and age.

Pass the values ​​of these properties as a constructor parameter.

Make getters that output the values ​​of each of our properties.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline