[英]A return function that returns a function in javascript
請我我的Java腳本有問題。
start_clock_ws : function(){
var that = this;
..decl
function init(){
if(socket.isReady() === true){
socket.send({ "time": 1});
console.log("clock started");
}else{
console.log("The other guy");
console.log("The ready state is",socket.isReady());
return that.start_clock(); //Here is my issue
}
};
function responseMsg(response){
..decl
}
this.run = function(){
console.log("the parent fired");
setInterval(init, 60000);
};
console.log("Its here");
init();
this.run();
this.clock_started = true;
socket.init({
onmessage : function(msg){
var response = JSON.parse(msg.data);
console.log("It fires here first");
if (response && response.msg_type === 'time') {
responseMsg(response);
}
}
});
},
start_clock : function(){
}
我的問題是上面的其他。 我檢查了isReady()的值,它是false。 然后,我返回了我的start_clock。 但是,當我執行時,它返回start_clock
並繼續運行我的this.run
。 上面的return
不應該強迫它繼續使用start_clock
離開代碼的其余部分嗎? 在不返回之前,它只是一個函數調用。 然后,我添加了返回值,希望它能起作用。 還在調試時。 我注意到我的socket.onmessage
函數由於ws請求而被多次調用。 然后我把它帶到下面的極端run
。
請幫助或解釋將不勝感激。 這對我來說還很新,很難理解問題。
調用init函數時,請嘗試以下操作:
if(init())
{
return;
}
如果該函數返回int值,那是因為您正在返回一個函數,並且代碼必須停止。 但是,如果沒有返回值(未定義),則代碼將繼續。
希望對您有所幫助!
嘗試這個:
// Check if clock_started and if not then run following code.
if(!init()){
this.run();
this.clock_started = true;
socket.init({
onmessage : function(msg){
var response = JSON.parse(msg.data);
console.log("It fires here first");
if (response && response.msg_type === 'time') {
responseMsg(response);
}
}
});
}
也
function init(){
if(socket.isReady() === true){
socket.send({ "time": 1});
console.log("clock started");
return false;
}else{
console.log("The other guy");
console.log("The ready state is",socket.isReady());
return that.start_clock(); //Here is my issue
}
};
我創建了一個簡單的小提琴用於說明。
Return
用於將值返回給調用函數。 您必須接收此值並進行相應處理。 在您的代碼中,您正在調用一個函數,但是不檢查返回值,因此它將繼續進行。
function welcome(name){ console.log("Hello " + name); } function permission(returnValue){ var str = returnValue?"You may proceed.":"You may not."; console.log(str); return returnValue } function proceed(){ console.log("Proceeding to next task.") } function run1(){ welcome('foo'); permission(false); proceed(); } function run2(){ welcome('foo'); if(permission(false)) proceed() else console.log("Permission denied."); }
<button onclick="run1()">Not Checking return value</button> <button onclick="run2()">Checking return value</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.