2016-12-28 6 views
0

ETA:私はこの質問がリンクされたものと重複しているとは思わない。私はプライベート変数(コードの下に示すように)を返す方法を知っていますが、この質問は同じオブジェクト内でプライベート関数を呼び出す方法に関するものでした。私は同じオブジェクト内からプライベート関数を呼び出すことができますか?

javascriptの関連情報を具体的に見つけることができません。私はオブジェクトを宣言し、そのオブジェクト内に4つの関数を宣言しています(3つはオブジェクトメソッドであり、もう1つはそうでないものです)。私は4番目をオブジェクトメソッドにして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 
    }); 
+0

[JavaScriptを:オブジェクトを返す関数]の可能な重複(http://stackoverflow.com/questions/12272239/javascript-function-returning-an-object) – Terry

答えて

0

あなたはつまり、オブジェクトの内部で別の変数を宣言することができます。 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 
    ); 
    } 
}; 
+0

これは完璧です。ありがとうございました! – Angie

関連する問題