访问构造函数中的函数变量

时间:2016-11-07 00:06:39

标签: javascript oop scope

我有一个构造函数(或类,如果你愿意),我的部分代码正在运行一个间隔。我试图清除间隔,但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;
    }
}

1 个答案:

答案 0 :(得分:-1)

您只需在功能对象中存储倒计时,然后将其绑定到,而不是

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;

  }
}

希望有所帮助