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

In JavaScript, there is no native support for access modifiers such as "protected" or "private" for class properties or methods. However, there are conventions that can be used to achieve similar functionality.

To call a protected property on an instance of a class in JavaScript, you can prefix the property name with an underscore ("_") to indicate that it is intended to be protected. Conventionally, the property should not be accessed outside of the class or its subclasses.

Here is an example:

index.tsx
class MyClass {
  constructor() {
    this._myProtectedProperty = 42;
  }
}

class MySubclass extends MyClass {
  logMyProtectedProperty() {
    console.log(this._myProtectedProperty);
  }
}

const instance = new MySubclass();
instance.logMyProtectedProperty(); // 42
268 chars
15 lines

In this example, _myProtectedProperty is a protected property that is set in the constructor of MyClass. MySubclass extends MyClass and defines a method logMyProtectedProperty that can be called to log the value of the protected property on an instance of the subclass. Note that the protected property should not be accessed directly outside of the class or its subclasses.

gistlibby LogSnag