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?
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);
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