Private Variables
This is how to almost make a private variable in javascript. It's a little wonky since you're creating a variable that's a part of a function and using it inside of an object being returned by said function.
by sderico
JavaScript
var myObject = (function(){
var myPrivateVariable = 0;
return {
getPrivateValue: function(){
return myPrivateVariable;
},
incrementPrivateValue: function(){
myPrivateVariable += 1;
}
};
}());
var myOtherObject = {
myPublicVariable: 0,
getPublicValue: function(){
return this.myPublicVariable;
},
incrementPublicValue: function(){
this.myPublicVariable += 1;
}
};
console.log(myObject.getPrivateValue());
myObject.incrementPrivateValue();
console.log(myObject.getPrivateValue());
console.log(myOtherObject.getPublicValue());
myOtherObject.myPublicVariable = 2000;
console.log(myOtherObject.getPublicValue());