An object user can use the public methods, but can't directly access private instance variables.
Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.
The private method of a class can only be accessible inside the class. The private methods cannot be called using the object outside of the class. If we try to access the private method outside the class, we'll get SyntaxError . Our private method can be declared by adding the # before the method name.
JavaScript allows you to define private methods for instance methods, static methods, and getter/setters. The following shows the syntax of defining a private instance method: class MyClass { #privateMethod() { //... } }
Is there a way to call "public" javascript functions from "private" ones within a class?
Check out the class below:
function Class()
{
this.publicMethod = function()
{
alert("hello");
}
privateMethod = function()
{
publicMethod();
}
this.test = function()
{
privateMethod();
}
}
Here is the code I run:
var class = new Class();
class.test();
Firebug gives this error:
publicMethod is not defined: [Break on this error] publicMethod();
Is there some other way to call publicMethod() within privateMethod() without accessing the global class variable [i.e. class.publicMethod()]?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With