I want to use a unique private variable for each "instance" (I hope that this is the right term in Javascript), but both instances appear to use the same private variable.
func = function(myName)
{
this.name = myName
secret = myName
func.prototype.tellSecret = function()
{ return "the secret of "+this.name+" is "+secret
}
}
f1 = new func("f_One")
f3 = new func("f_3")
console.log(f3.tellSecret()) // "the secret of f_3 is f_3" OK
console.log(f1.tellSecret()) // "the secret of f_One is f_3" (not OK for me)
I saw a solution but
this would mean duplicating the function on every instance, and the function lives on the instance, not on the prototype.
Another author says about the same solution
That's still not quite traditional classly Javascript, which would define the methods only once on Account.prototype.
So, is there a solution where
- every instance can have unique values for
secret
secret
is only accessible for methods that are defined in the constructor and- functions are not duplicated for every instance
?