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

In JavaScript, there is no built-in concept of access modifiers like public, private, or protected as in other OOP languages like Java or C#. However, it is possible to simulate protected access by convention, using an underscore prefix for the method or property that should be considered protected.

To call a protected static method on an instance of a class in JavaScript, you can use the following syntax:

index.tsx
class MyClass {
  static _myProtectedStaticMethod() {
    console.log("This is my protected static method");
  }
}

class MySubclass extends MyClass{
  constructor() {
    super();
    MyClass._myProtectedStaticMethod();
  }
}

const myInstance = new MySubclass(); // Outputs: "This is my protected static method"
314 chars
15 lines

In this example, _myProtectedStaticMethod is a protected static method defined on the MyClass class. It can be accessed by the MySubclass subclass because it extends MyClass.

To call the protected static method from within the constructor of MySubclass, you need to use the class name (MyClass) instead of this, since it is a static method, and _myProtectedStaticMethod can be accessed because MySubclass extends MyClass.

Note that this is not true encapsulation and a bad practice in general, as the _-prefix convention is just a naming convention rather than a true access modifier.

gistlibby LogSnag