小编B K*_*yes的帖子

范围和异步JavaScript

我最近在其中,至少根据我的JavaScript知识遇到了一个问题,在工作中,我回来是不可能的结果.我希望有人可以解释这里发生的事情,以及为什么实际结果与我的预期结果不同.

控制台中的预期结果

id: a , x: 1
id: b , x: 1
id: c , x: 1
Run Code Online (Sandbox Code Playgroud)

控制台中的实际结果

id: c , x: 1
id: c , x: 2
id: c , x: 3
Run Code Online (Sandbox Code Playgroud)

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");
Run Code Online (Sandbox Code Playgroud)

javascript scope asynchronous

6
推荐指数
1
解决办法
494
查看次数

标签 统计

asynchronous ×1

javascript ×1

scope ×1