[Yes, I have read several answers to similar questions, but didn't really get the answer I'm looking for, so I'm going to ask my question anyway.]
In the code below, how can I place the methods setSecret and tellSecret in Secret's prototype while still maintaining access to the private instance variable _secret, and also producing the same output?
I tried this (see jsbin) which placed the methods in the prototype, but changed the output.
function Secret() {
// ===== private =====
var _secret;
// ===== public =====
this.setSecret = function (secret) {
_secret = secret;
};
this.tellSecret = function () {
console.log(_secret);
};
}
var secretA = new Secret();
var secretB = new Secret();
secretA.setSecret("AAA");
secretB.setSecret("BBB");
setTimeout(function () {
console.log("Secret A");
secretA.tellSecret();
console.log("Secret B");
secretB.tellSecret();
}, 1000);
// ===== output =====
Secret A
AAA
Secret B
BBB