Revealing Prototype Pattern private variable problem
The problem I'm facing is: how can I preserve state with private variables, that are used across the shared/singleton functions?
by lucky3
HTML
Press F12 to see console log.
JavaScript
var MyClass = function () {};
MyClass.prototype = function () {
var v;
var setValue = function (inVal) {
v = inVal;
doSomething();
};
var doSomething = function () {
v += "123";
};
var getValue = function () {
return v;
};
return {
SetValue: setValue,
GetValue: getValue
};
}();
var logToConsole = function (caller, expected, actual) {
console.log("Caller " + caller + " is expecting: " + expected + ", actual value is: " + actual);
};
// tests
console.clear();
var m1 = new MyClass();
m1.SetValue("a");
logToConsole("m1", "a123", m1.GetValue());
var m2 = new MyClass();
m2.SetValue("b");
logToConsole("m2", "b123", m2.GetValue());
console.log("here should be the problem:");
logToConsole("m1", "a123", m1.GetValue());
console.log("m2.v should not be accessible:");
console.log(m2.v);
// now to overriding of MyClass
MyClass.prototype = function () {
var setValue = function (inVal) {
this.v = inVal;
doSomething.call(this);
};
var doSomething = function () {
this.v += "123";
};
var getValue = function () {
return this.v;
};
return {
SetValue: setValue,
GetValue: getValue
};
}();
console.log("Tests with overriden MyClass.prototype:");
// tests
var m3 = new MyClass();
m3.SetValue("c");
logToConsole("m3", "c123", m3.GetValue());
var m4 = new MyClass();
m4.SetValue("d");
logToConsole("m4", "d123", m4.GetValue());
console.log("here should now work OK:");
logToConsole("m3", "c123", m3.GetValue());
console.log("m4.v is now public:");
console.log(m4.v);
console.log("it's the same as having this.v = null; in constructor, and I don't want that.");