I am trying to figure out how to have a private instance variable on my class that gets set by a parameter of a public method. In this case, though; it seems that outside of somePublicMethod myPrivateVar will be undefined. How can achieve what I am trying to do ?
MyClass = function() {
var myPrivateVar;
this.somePublicMethod(myPrivateVar) {
myPrivateVar = myPrivateVar //????
}
this.someOtherPublicMethod() {
somePrivateMethod();
}
function somePrivateMethod() {
myPrivateVar++;
}
}
The issue is you’re shadowing the
var myPrivateVarby giving the argument the same name, so only the argument variable is in scope:You’ll need to give one of them a different name to avoid shadowing:
Otherwise, you’ll need to contain one of them somehow: