我可以在同一个对象javascript中调用私有函数

时间:2016-12-28 18:32:08

标签: javascript jquery object private-methods

ETA:我不相信这个问题与链接的问题重复。我知道如何返回一个私有变量(如下面的代码所示),这个问题是关于如何在同一个对象中调用私有函数。

我无法专门为javascript查找相关信息。我有一个声明的对象,并且在该对象中我声明了四个函数(三个是对象方法,另一个不是)。我想让第四个函数成为一个对象方法,这样我就可以从jquery中单独调用它(timer.displayTime ();)但是当我这样做时startIntervalTimer使用该函数停止工作。我正在努力做甚么可能吗?

var startStopTime = function() {

 //This function is currently called inside startIntervalTimer(); 
 function displayTime() {
    //Display correct time
  };

//I WANT SOMETHING LIKE THIS INSTEAD BUT (SEE startIntervalTimer)
this.displayTime = function() {
//Display correct time
}

  var intervalTimer; 
  this.startIntervalTimer = function() {
    console.log(timeSetMS);
    intervalTimer = setInterval(function() {
      if(timeSetMS > 0) {
       timeSetMS -= 1000;
      displayTime(); //THIS IS WHERE AND HOW IT IS CALLED
      this.displayTime(); //THIS IS WHAT I'M GOING FOR, BUT IT WON'T WORK
      console.log(timeSetMS); 
      } else if(timeSetMS <= 0) {
        clearInterval(intervalTimer);
        console.log("timer stopped");
      }  
    }, 1000
    );
  }   
};

然后在我的jquery中:

var timer = new startStopTime();
$("#timer-container,  #timer-label").click(function() {
    if(power == "off") {
      power = "on"; 
      timer.startIntervalTimer();
    } else if (power == "on") {
      power = "off";
      timer.stopTimer();
    }
   });

//I want to add this, below

$("#session-length").click(function() {
    //Change the display
    timer.displayTime();
    displayTime(); // This won't work obviously because it's out of scope
  });

1 个答案:

答案 0 :(得分:1)

您可以在对象内声明另一个变量,即。 self

var startStopTime = function() {
  //declare self
  var self = this;

  this.displayTime = function() {
  //Display correct time
  }

  var intervalTimer; 
  this.startIntervalTimer = function() {
    console.log(timeSetMS);
    intervalTimer = setInterval(function() {
      if(timeSetMS > 0) {
       timeSetMS -= 1000;
      displayTime(); 
      self.displayTime(); // use self instead
      console.log(timeSetMS); 
      } else if(timeSetMS <= 0) {
        clearInterval(intervalTimer);
        console.log("timer stopped");
      }  
    }, 1000
    );
  }   
};