Public and Private Methods in JavaScript

Public Members can be accessed anywhere using the "." notation.

Private Members can only be accessed within a constructor and public method.

Public methods and variables are declared using the "this" keyword like "this.variableName".

A Public method is accessed using a constructor; this technique is usually used to initialize public instance variables.

var objPublicPrivateClassg = new PublicPrivateClass();

Code

/*Comment

<CodeItem type="Method">Class Name</CodeItem>

<summary>Define the Class name as a function</summary>

<params>

</params>

<return></return>

Comment*/

function PublicPrivateClass() {

    //PublicMethods

    this.publicMethods = {

        /*Comment

        <CodeItem type="Method">InitializePageControlEvents</CodeItem>

        <summary>Initialize the control</summary>

        <params>

        </params>

        <return></return>

        Comment*/

        InitializePageControlEvents: function () {

            privateMethods.PrivateTestMethod();

        }

    };

    // Private Methods

    privateMethods = {

        /*Comment

        <CodeItem type="Method">PrivateTestMethod</CodeItem>

        <summary>Show the alert Message</summary>

        <params>

        </params>

        <return></return>

        Comment*/

        PrivateTestMethod: function () {

            alert("Calling Private Method.");

        },

 

        PrivateTestMethod2: function () {

            alert("PrivateTestMethod2");

        } 

    };

}

 

HTML Code

Calling a Public Method:

<script type="text/javascript">

    function CallMethod() { 

        try {            

            var objPublicPrivateClassg = new PublicPrivateClass();

            //InitializePageControlEvents is Public method

            objPublicPrivateClassg.publicMethods.InitializePageControlEvents(); 

        }

        catch (err) {

 

            alert(err.message);

        } 

    }

</script>

HTML Code

Calling a Public Method:
 

<script type="text/javascript">

    function CallMethod() { 

        try {

            

            var objPublicPrivateClassg = new PublicPrivateClass();

            //InitializePageControlEvents is Public method

            objPublicPrivateClassg.publicMethods.InitializePageControlEvents(); 

        }

        catch (err) { 

            alert(err.message);

        } 

    }

</script>


Output
Public-and-private-methods-in-JavaScript1.jpg
 

<script type="text/javascript">

    function CallMethod() { 

        try { 

            var objPublicPrivateClassg = new PublicPrivateClass();

            //InitializePageControlEvents is Private method

             objPublicPrivateClassg.privateMethods.PrivateTestMethod(); 

        }

        catch (err) { 

            alert(err.message);

        } 

    }

</script>


Output
Output-Public-and-private-methods-in-JavaScript.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all