call a private property on an instance of a class in javascript

To call a private property on an instance of a class in JavaScript, you would need to create a getter method inside the class that returns the value of the private property.

Here's an example:

index.tsx
class MyClass {
  constructor() {
    let privateProperty = 'I am a private property';
    
    this.getPrivateProperty = function() {
      return privateProperty;
   }
  }
}

let myInstance = new MyClass();
console.log(myInstance.getPrivateProperty()); // Output: "I am a private property"
292 chars
13 lines

In this example, we create a class called MyClass and inside the constructor, we define a private property called privateProperty. We then define a getter method called getPrivateProperty that returns the value of privateProperty. Since the getter method is defined inside the class, it has access to privateProperty.

To call the private property on an instance of MyClass, we create a new instance of the class and call the getPrivateProperty method on it. The method returns the value of the private property, allowing us to access it without directly referring to the private property itself outside of the class.

gistlibby LogSnag