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

In JavaScript, we can't define access modifiers like protected or private to properties or methods in ES6 classes. However, we can still use the common convention of surrounding a property or method with an underscore to indicate that it's intended to be protected.

To call a protected static property on an instance of a class, we need to use the class name instead of the instance name, like so:

index.tsx
class MyClass {
  static _myProtectedProperty = 'some value';
}

const myInstance = new MyClass();

console.log(MyClass._myProtectedProperty); // "some value"
159 chars
8 lines

In this example, we define a protected static property _myProtectedProperty on the MyClass class. Then, we create an instance of MyClass called myInstance. Finally, when we want to access the value of _myProtectedProperty, we use MyClass._myProtectedProperty instead of myInstance._myProtectedProperty.

gistlibby LogSnag