【问题标题】:accessing function variables in a constructor在构造函数中访问函数变量
【发布时间】:2016-11-07 00:06:39
【问题描述】:

我有一个构造函数(或类,如果你愿意的话),我的部分代码正在运行一个间隔。我正在尝试清除间隔,但在 countDown 函数中无法访问 countDown 变量。

请注意: countDownstartTimer 函数都在构造函数中。

代码如下:

this.startTimer = function() {
    if (!isOn) {
        timeFormatter();
        if (timeArray[0] === "0") {
            return error(" You need to work longer than that! ")
        }
        isOn = true;
 var startCountDown = setInterval(this.countDown.bind(this),1000);
    }
}

this.countDown = function() {
    //Once timer ends, stop function.
    if (timeArray[0] === 0
     && timeArray[2] === 0
     && timeArray[3] === 1) {
        element.innerHTML = 0;
        counter = 0;
        isOn = false;
        clearInterval(startCountDown) //I get error here. countDown is not accessible.
        return null;
    }
}

【问题讨论】:

  • 如果你在 startTimer 函数中访问 c​​ountDown ,它只在这个范围内可用。如果您希望 var 可全局访问,请全局定义它(在函数范围之外)。
  • 添加到@Lupinity 的评论:将其声明为您班级的成员。还有,不要叫countDown,会和countDown函数冲突
  • 如果我在函数之外定义它,那么它会更早触发,我需要它在启动计时器函数中触发。我想避免使用未定义的全局变量。
  • @Tibrogargan 你能解释一下你的意思吗?
  • @theNeighbourhoodGhost countDownthis 的属性。即使您在全局范围内或作为其中的成员声明了一个单独的变量,您也会遇到名称冲突。您不能有两个具有相同名称的标识符 - 一个会隐藏另一个。您尤其不能拥有两个同名的属性。您无法访问在 startTimer 函数中声明的var countDown,因为该声明的范围是本地的。同样,即使它是全局的,您也无法访问它,因为 this.countDown 会隐藏它

标签: javascript oop scope


【解决方案1】:

您可以简单地将 countdown 存储在您的函数对象中,然后将其绑定到 this 而不是 this

this.countdown = setInterval()

然后将函数绑定到 this

this.startTimer = function(){
    if(!isOn){
    timeFormatter();
        if(timeArray[0] === "0"){
            return error(" You need to work longer than that! ")
        }
    isOn = true;    
    this.countDown = setInterval(this.countDown.bind(this),1000);
    }
}.bind(this); // this

this.countDown = function () {

  //Once timer ends, stop function.
  if (timeArray[0] === 0 && timeArray[2] === 0 && timeArray[3] === 1) {
    element.innerHTML = 0;
    counter = 0;
    isOn = false;
    clearInterval(this.countdown);
    return null;

  }
}.bind(this); // and this one

或将变量存储在更高级别

var countDown; // this

this.startTimer = function(){
    if(!isOn){
    timeFormatter();
        if(timeArray[0] === "0"){
            return error(" You need to work longer than that! ")
        }
    isOn = true;    
    countDown = setInterval(this.countDown.bind(this),1000);
    }
}

this.countDown = function () {

  //Once timer ends, stop function.
  if (timeArray[0] === 0 && timeArray[2] === 0 && timeArray[3] === 1) {
    element.innerHTML = 0;
    counter = 0;
    isOn = false;
    clearInterval(countDown) //I get error here. countDown is not accessible.
    return null;

  }
}

希望有帮助

【讨论】:

  • 你真的测试过这段代码吗?两个版本都会失败
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
相关资源
最近更新 更多