I am trying to learn more about how to create private variables and methods in JavaScript. The code below seems to work but I feel as though there may be a more efficient way to do this. Any suggestions?
var CountObject = (function () {
function countObject() {
// private variables
var _a = 1;
var _b = 2;
var _c = _a + _b;
// private method
addTo = function (num) {
_c = _c + _a + _b + num;
return _c;
}
}
// public method
countObject.prototype.add = function (num) {
return addTo(num);
};
return countObject;
}());
var testObject1 = new CountObject();
console.log(testObject1.add(1));
//output 7
console.log(testObject1.add(1));
//output 11
console.log(testObject1.add(1));
//output 15
var testObject2 = new CountObject();
console.log("testobject2:" + testObject2.add(100));
//output testobject2:106