Reputation: 131
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++;
}
}
Upvotes: 1
Views: 321
Reputation: 268364
Have you considered taking a slightly different route?
var MyClass = function(){
var bar = "private";
return {
setBar: function( newBar ) { bar = newBar; },
getBar: function() { return bar; }
}
};
When you new-up an instance of this class, the bar property will be private. However, it will still be accessible by the public setBar
and getBar
methods.
var inst = new MyClass;
console.log( inst.bar ); // undefined
console.log( inst.getBar() ); // 'private'
inst.setBar( 'accessible' );
console.log( inst.getBar() ); // 'accessible'
Upvotes: 0
Reputation: 123473
The issue is you're shadowing the var myPrivateVar
by giving the argument the same name, so only the argument variable is in scope:
this.somePublicMethod = function(myPrivateVar) {
myPrivateVar = myPrivateVar; // sets the argument to itself
}
You'll need to give one of them a different name to avoid shadowing:
this.somePublicMethod = function(inputVar) {
myPrivateVar = inputVar;
};
Otherwise, you'll need to contain one of them somehow:
MyClass = function () {
var locals = {
myPrivateVar: null
};
this.somePublicMethod = function (myPrivateVar) {
locals.myPrivateVar = myPrivateVar;
};
function somePrivateMethod() {
locals.myPrivateVar++;
}
};
Upvotes: 2
Reputation: 91329
Use this.myPrivateVar
:
this.somePublicMethod = function(myPrivateVar) {
this.myPrivateVar = myPrivateVar;
}
To call the private method within the context of this
, you can use:
this.somePublicMethod = function(myPrivateVar) {
this.myPrivateVar = myPrivateVar;
somePrivateMethod.call(this); // pass this as the context of the private method
}
function somePrivateMethod() {
this.myPrivateVar++;
}
Upvotes: 1