簡體   English   中英

范圍和異步JavaScript

[英]Scope and Asynchronous JavaScript

我最近在工作中遇到了一個問題,至少根據我對JavaScript的了解,我得到了一個不可能的結果。 我希望有人可以解釋這里發生的事情,以及為什么實際結果與我的預期結果不同。

控制台中的預期結果

id: a , x: 1
id: b , x: 1
id: c , x: 1

控制台中的實際結果

id: c , x: 1
id: c , x: 2
id: c , x: 3

function MyClass(id)
{
    var x = 0;

    return function()
    {
        return function()
        {
            x += 1;
            console.log("id: ", id, ", x: ", x);
        }
    }
}


function DoStuff(id)
{
    var q = MyClass(id);
    response_callback = q();
    setTimeout(function(){ response_callback(); }, 50);
}

DoStuff("a");
DoStuff("b");
DoStuff("c");
 response_callback = q(); 

這個。 in any scope, so it's implicitly in the global scope... 您沒有在任何范圍內聲明 ,因此它隱含在全局范圍內...

這意味着每次調用DoStuff()時都會覆蓋它。 認為你已經獲得了三個不同的功能並被召喚,但只有一個......

 var response_callback = q(); // should set you back on track

當然,你現在擁有這種結構化的方式有點浪費了MyClass返回一個返回函數的函數的能力。 你實際上可以寫:

function DoStuff(id)
{
  var q = MyClass(id);
  // ... do other strange and horrible things with q ...
  setTimeout(q(), 50);
}

......並且在沒有不必要的封閉的情況下看到相同的結

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM