⊗jsOpIhPrM 34 of 60 menu

Private Methods in Inheritance in OOP in JavaScript

Private methods are not inherited. This is done on purpose, so as not to violate encapsulation. Let's look at an example. Let's say we have the following parent class with a private method:

class User { setName(name) { this.name = name; } getName() { return this.#capeFirst(this.name); } #capeFirst(str) { return str[0].toUpperCase() + str.slice(1); } }

Let the following class inherit from the parent class:

class Student extends User { setSurn(surn) { this.surn = surn; } getSurn() { return this.surn; } }

Let's say a child wants to use a private method of the parent. JavaScript will not allow this and will throw an error:

class Student extends User { setSurn(surn) { this.surn = surn; } getSurn() { return this.#capeFirst(this.surn); // there will be an error } }

Try using the private method of the parent in the Employee class.

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