In my JavaScript code, I am trying to have a unique private variable for each "instance," but it seems that both instances end up using 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 came across a possible solution, but
this would mean duplicating the function on every instance, and the function lives on the instance, not on the prototype.
Another developer mentioned a similar solution in this post
That's still not quite traditional class-based JavaScript, which would define the methods only once on Account.prototype.
So, I'm wondering if there is a way to achieve:
- have every instance with unique values for
secret
- ensure that
secret
is only accessible to methods defined in the constructor, and - avoid duplicating functions for each instance
Is there a solution for this?