Следите за новинками
в нашем Telegram канале. Жми, чтобы подписаться:)
⊗jsOpIhPtP 38 of 60 menu
◀ ▶

Protected Properties in OOP in JavaScript

Let's also introduce protected properties. Let's also start their names with an underscore. Let's look at an example. Let's make a parent class with a protected property containing age:

class User { setAge(age) { this._age = age; } getAge() { return this._age; } }

In the descendant class we will create a method that increases the age by one:

class Student extends User { incAge() { this._age++; } }

Rewrite the following code using a protected property:

class User { #name; setName(name) { this.#name = name; } getName() { return this.#name; } } class Employee extends User { setName(name) { if (name.length > 0) { this.#name = name; } } }
← →
↑
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