javascript - 我可以从同一个对象 javascript 中调用私有(private)函数吗

标签 javascript jquery object private-methods

预计到达时间:我不认为这个问题与链接的问题重复。我知道如何返回私有(private)变量(如下代码所示),这个问题是关于如何在同一对象中调用私有(private)函数。

我无法专门找到 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
  });

最佳答案

您可以在对象内部声明另一个变量,即。 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
    );
  }   
};

关于javascript - 我可以从同一个对象 javascript 中调用私有(private)函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367775/

相关文章:

javascript - 处理 bool 值

javascript - 使用jquery脚本时无法在PHP中调用html标签

javascript - 点击目标数据 'id' + 1 上的 jQuery

javascript - .Net Core 2 在 View 中将 C# 变量转换为 Javascript

javascript - 附加按钮输入并删除不工作的 parent

javascript - 根据另一个对象数组的值创建对象数组

javascript - 在模态中显示原始 JSON

javascript - jQuery 插件 fullPage.js 的 slider 组件的自定义下一个/上一个箭头按钮

jquery - 删除悬停样式?

javascript - 在通过 MyObject.prototype.method 和 'this' 变量定义的对象方法中使用 jQuery