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.tsx476 chars15 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