Reputation: 770
I am using a setter to give a variable in my class a new value. However, after the value is set and is used in another method the variable defaults back to its original value.
The following code is not the actual code in my project....
var canContinue = false;
classXX.prototype.check = function() {
if(canContinue){
//do something
}
}
classXX.prototype.init = function() {
canContinue = false;
}
classXX.prototype.setCanContinue(val) {
canContinue = val;
}
return {
getInstance: function() {
_instance = new classXX();
return _instance;
}
};
After the class has been instantiated canContinue = true; If i make the call classXX.setCanContinue(false) then the check function still sees canContinue as true.
Am I missing something?
Upvotes: 0
Views: 111
Reputation: 2547
You can do something like below, but the canContinue
variable will be shared between all the instances. if you want that to be specific to each instance then you should declare it inside constructor function.
var classXXfactory = (function() {
var canContinue = false;
function classXX() {
}
classXX.prototype.check = function() {
if (canContinue) {
console.log('continue');
}
}
classXX.prototype.init = function() {
canContinue = false;
}
classXX.prototype.setCanContinue = function(val) {
canContinue = val;
}
classXX.prototype.getCanContinueValue = function() {
return canContinue;
}
return {
getInstance: function() {
_instance = new classXX();
return _instance;
}
};
}());
console.log('############### First Instance');
var inst1 = classXXfactory.getInstance();
console.log(inst1.getCanContinueValue());
inst1.setCanContinue(true);
console.log(inst1.getCanContinueValue());
console.log('############### Second Instance');
var inst2 = classXXfactory.getInstance();
console.log(inst2.getCanContinueValue());
inst2.setCanContinue(true);
console.log(inst2.getCanContinueValue());
console.log('############### Setting value in second Instance');
inst2.setCanContinue("SETTGIN IN SECOND INST2");
console.log('############### Getting value from both Instances');
console.log(inst1.getCanContinueValue());
console.log(inst2.getCanContinueValue());
Upvotes: 2