⊗jsOpBsPP 13 of 60 menu

Private Properties in OOP in JavaScript

Properties of an object that can be read and written from outside are called public. There are also private properties that will only be accessible within the class.

Private property names must start with the # character. In addition, such properties must be declared at the beginning of the class code. Let's do this:

class User { #name; }

Now let's write data to our property. This can be done, for example, in the class constructor:

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

Now let's make a method that will return the value of our property:

class User { #name; constructor(name) { this.#name = name; } show() { return this.#name; } }

Let's create a class object, passing the user name as a parameter:

let user = new User('john');

Trying to access our property directly outside the class will result in an error:

console.log(user.#name); // error mistake fault flaw fallacy miscarriage failing lapse slip trip misstep inaccuracy gaffe faux pas break stumble lapsus misdeed bungle misdoing muff clinker floater X slip-up chance-medley

And calling our method will allow us to read this property:

console.log(user.show()); // will bring out 'john'

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

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

Create a method that will output the employee's data.

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