Search code examples
javascriptjqueryobjectprivate-methods

can I call a private function from within the same object javascript


ETA: I don't believe this question is a duplicate to the one linked. I know how to return a private variable (as shown below in the code), this question was about how to call a private function within the same object.

I'm having trouble finding relevant information for javascript specifically. I have an object declared and within that object I have declared four functions (three that are object methods and one that is not).I want to make the fourth one an object method so that I can call it separately from jquery (timer.displayTime(); ) but when I do that startIntervalTimer use of the function stops working. Is what I'm trying to do even possible?

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

and then in the jquery I have:

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

Solution

  • You can declare another variable inside the object, ie. 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
        );
      }   
    };