2012-02-23 118 views
1

這是一個簡單的腳本來檢索'CouchDB'會話並獲取用戶信息。它利用'couch.j'使用'jQuery'。我一直在使用JavaScript一段時間,但我無法弄清楚如何傳遞返回值然後使用它們。Javascript函數返回會話對象

$(document).ready(function() { 
    this.ctx = getCtx(); //it doesn’t appear that this is actually assigning a variable 
    console.log(this.ctx); //this returns 「undefined」 
}); 

function getCtx(){ 

    $.couch.session({ 
     async: false, 
     success: function(r) { 

       ctx = r.userCtx; 
       if (ctx != null){ //I added this check because otherwise ctx was returning undefined. 

        console.log("returning ctx: "+ctx); 
//Log says: returning ctx: [object Object] 
        return ctx;       
//I know this is returning an object, because of the line above 

       } 
     } 
    }); 
}; 

是什麼絆倒了我更是在$(document).ready功能的console.log語句在getCtx()函數返回的console.log語句之前返回「不確定」。這意味着它不會給getCtx()時間執行並實際獲得會話。

+0

你需要成功的函數來設置getCtx函數中的局部變量,以便它可以返回它,你getCtx當前不返回任何東西。 – Dampsquid 2012-02-23 22:07:52

回答

2

的您可以分配移動到AJAX調用成功功能,像這樣

$(document).ready(function() { 
    getCtx(this);  
}); 

function getCtx(obj){ 

    $.couch.session({ 
     async: false, 
     success: function(r) { 

       ctx = r.userCtx; 
       if (ctx != null){   

        console.log("returning ctx: "+ctx); 
        obj.ctx = ctx;       

       } 
     } 
    }); 
}; 
+0

所以我試着去做你在暗示的東西,但是如果我在$(document).ready函數中添加其他東西,它們會嘗試在getCtx(this);之前執行。例如,如果我把一個'console.log(this.ctx);' 'getCtx(this)'後面的語句;'輸出將是兩個日誌,一個'undefined',然後一個'返回ctx:[object Object]'。這似乎與JavaScript編譯/解釋工作的順序有關,但我不理解它。 – 2012-02-24 03:33:06

+0

謝謝大家的幫助。 – 2012-02-24 19:23:31

0

嘗試:

$(document).ready(function() { 
    var ctx = getCtx(); 
    console.log(ctx); 
}); 
1

您需要分配成功,函數內部CTX變種,而不是返回值