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

In JavaScript, we can't create access modifiers like public, private, and protected like other object-oriented programming languages. However, we can somewhat emulate protected behavior in JavaScript by using closures.

Here's an example of how to call a protected method on an instance of a class in JavaScript:

index.tsx
class MyClass {
  #protectedMethod() {
    console.log('This method is protected and cannot be called outside the class');
  }
  
  callProtectedMethod() {
    this.#protectedMethod(); // We can call the protected method within the class
  }
}

const myObj = new MyClass();

myObj.callProtectedMethod(); // This will call the protected method within the class
myObj.#protectedMethod(); // This will throw an error because we cannot call the protected method outside the class
476 chars
15 lines

In the above code, we're using the private class field syntax to declare a private / protected method, denoted by the # symbol before the method name. We can call this method within the class by using this.#protectedMethod(). However, if we try to call this method outside the class, like myObj.#protectedMethod(), we'll get a syntax error.

Note that this is not true encapsulation or access modifiers, but more of a convention. It's up to the programmer to follow this convention and not call protected / private methods outside of the class.

gistlibby LogSnag