Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Hiding in Javascript

Tags:

javascript

oop

In the Java Programming language the private keyword is used for data hiding - a field or a method marked as private is not visible outside the classes or the subclasses.

How is that achieved in javascript?

like image 389
oneiros Avatar asked Jul 17 '12 15:07

oneiros


1 Answers

In JavaScript standard way is to use Module Pattern as shown below..

var testModule = (function () {

    var myPrivateVar = 0;

    var myPrivateMethod = function (someText) {
        console.log(someText);
    };

    return {

        myPublicVar: "foo",

        myPublicFunction: function (bar) {
            myPrivateVar++;
            myPrivateMethod(bar);
        }

    };
})();

Usage: In the above code an object is returned which contains a variable (myPublicVar) and a function(myPublicFunction). Inside this function you can access the inner variable (myPrivateVar) and inner function(myPrivateMethod) but not from outside.

var mod = new testModule();
mod.myPublicFunction(param);
like image 123
Amitabh Avatar answered Oct 17 '22 01:10

Amitabh