Skip to main content

Javascript Access Control

Public methods and variables of class instance, is capable to use those properties outside the class. And inherit class objects also can be use public method of base class. In this section given example of privateproperties which is protect data in outside the class or inherit class.

#variableName = value; //private variable

# symbol are define private instance variable which are cannot access outside the class.

Example of private properties

class Records{
  //private variable
  #images=0;
  #docs=0; 
  constructor(images,docs){
    this.#images=images;
    this.#docs=docs;
  }
  //Access private data by methods
  get doc(){
    //return docs
    return this.#docs;
  }
  get image(){
    //return images
    return this.#images;
  }
}
let manager = new Records(10,20);
//console.log(manager.#docs); //error - private property
//console.log(manager.#images); //error - private property

//Access by class method
console.log("Docs : ",manager.doc); //10
console.log("Images : ",manager.image); //20
Example Class private Properties
Docs :  20
Images :  10




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment