变量没有保持新价值

时间:2015-05-27 16:34:43

标签: javascript class encapsulation

我正在使用setter为我的类中的变量赋一个新值。但是,在设置值并在另一个方法中使用后,变量默认返回其原始值。

以下代码不是我项目中的实际代码....

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;
        }
    };

在实例化类之后,canContinue = true;如果我调用classXX.setCanContinue(false),那么check函数仍然将canContinue视为true。

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作,但canContinue变量将在所有实例之间共享。如果你希望它特定于每个实例,那么你应该在构造函数中声明它。

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());