【问题标题】:javascript variable scope: returning variables from nested functions?javascript变量范围:从嵌套函数返回变量?
【发布时间】:2012-06-24 09:30:54
【问题描述】:

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

但它并没有真正帮助我(或者我太笨了,无法理解)。

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

非常感谢任何 cmets/指针/答案!

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() 来处理异步函数调用并基本上使它们同步?如果任何读过这篇文章的人都知道我很想知道的答案。谢谢。

【问题讨论】:

  • 很可能,因为function(stuff) 从未运行过。您的范围界定看起来不错。这里没有任何东西可以证明设置baby="old" 的代码行曾经被执行过。 someVar 可能为 false,或者 someAPI 永远无法调用您传递给它的函数。
  • 好吧,我最初确实用 alert() 检查了这个函数正在被调用。我认为 API 函数的 async 元素是解决方案。

标签: javascript nested scope settimeout anonymous-function


【解决方案1】:

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);
});

【讨论】:

  • 谢谢胡安,这绝对让我明白了。总是与异步作斗争。
  • @tim BTW,class 是保留关键字,不应用作属性名称(除非您始终将其与 someAPI["class"]() 一起使用,我希望这不是方法的真实名称你在打电话
  • Juan,谢谢,是的,我知道“类”——为了清楚起见,我正在简化代码示例。
【解决方案2】:

在这里我可以认为你的

 someAPI.class();

必须是与事件相关的函数(如单击、鼠标悬停等)。所以它里面的函数只有在相关事件发生时才会执行,从而改变变量的值。但我认为事件不会发生,因此变量不会改变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-03
    • 2015-07-02
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多