javascript变量范围:从嵌套函数返回变量?

时间:2012-06-22 04:25:50

标签: javascript nested scope settimeout anonymous-function

我看了这个:Returning values from nested functions in Javascript

但它并没有真正帮助我(或者我太愚蠢了)。

我的变量范围以某种方式关闭,我不明白为什么。我的alert()没有按预期运行。试图在所有行上添加注释来解释我在想什么。

非常感谢任何评论/指点/答案!

var g = {}; / is a large object with all kinds of other stuff and functions in it

g.ding = function(){ // my problem function
 var baby = 'young'; // i thought I set a local var here
    if(someVar==true) { // standard issue if statement
        someAPI.class( // using an API that uses a function as its attribute
            function(stuff){ // my anonymous function
                baby = 'old'; // setting the var to something
            }
        );
    }
    return baby; // returning the var
}

alert( g.ding() ); // i expect it to say "old" but it keeps saying "young". why?

新编辑: Juan接受的答案很棒,但是有没有办法使用 setTimeout()来处理异步函数调用并基本上使它们同步?如果有人读到这个知道我想知道的答案。感谢。

2 个答案:

答案 0 :(得分:6)

someAPI.class(function(){})的调用可能是异步的,这意味着当someAPI.class()返回且变量尚未更改时,您传入的函数可能尚未被调用。

解决方案是在回调

中传回变量
g.ding = function(callback){ 
    var baby = 'young';
    if(someVar) {
        someAPI.class(
            // There's no guarantee of when this function is called
            function(stuff){
                baby = 'old';
                // Call the callback, it's like a return, for async functions
                callback(baby);
            }
        );
    }
    // the inner function probably wasn't called yet, 
    // doesn't make sense to return this here
    // return baby;
}

// Then you'd call it like this, as soon as you use an async function
// all the functions that call it have to use callbacks for return values
g.ding(function(value){
    alert(value);
});

答案 1 :(得分:0)

在这里我可以认为你的

 someAPI.class();

必须是与事件相关的功能(如点击,鼠标悬停等)。因此,只有当相关事件发生时才会执行其中的函数,从而更改变量的值。但我认为事件不会发生,因此变量不会改变。