Javascript函数返回会话对象

问题描述:

这是一个简单的脚本来检索'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

的您可以分配移动到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

尝试:

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

您需要分配成功,函数内部CTX变种,而不是返回值