Skip to content

Instantly share code, notes, and snippets.

@schell
Last active September 26, 2015 06:57
Show Gist options
  • Save schell/1057763 to your computer and use it in GitHub Desktop.
Save schell/1057763 to your computer and use it in GitHub Desktop.
JS private methods through closures.
function PrivateThing() {
var privateVar1 = 0;
var privateVar2 = 0;
function privateFunction() {
alert('i am in a closure private var one ='+privateVar1.toString());
privateVar1++;
}
function privateFunctionTwo() {
alert('nothing outside the object created by this function can reach me. private var two ='+privateVar2.toString());
privateVar2++;
}
this.publicFunction = function() {
privateFunction();
privateFunctionTwo();
alert('everything can reach me...vars = '+privateVar1.toString()+' '+privateVar2.toString());
};
this.publicProperty = 'i am public property';
}
var object = new PrivateThing();
object.publicFunction();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment