Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing "Public" methods from "Private" methods in javascript class

Tags:

People also ask

Can a public method access a private method?

An object user can use the public methods, but can't directly access private instance variables.

Does JavaScript have public and private methods?

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.

Can we access private method from outside class JavaScript?

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.

Can you have private methods in JavaScript?

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()]?