简体   繁体   English

为什么在回调中声明var不能定义参数? (起重)

[英]Why does declaring a var inside a callback undefine the parameter? (Hoisting)

$(function() {
    foo1("text");
    foo2("text");
}) 

function callback(func) {
    func();
}

function foo1(bar) {
    callback(function() {
        console.log(bar);       // "text"
        bar = "derp";
        console.log(bar);       // "derp"
    })
}

function foo2(bar) {
    callback(function() {
        console.log(bar);       // undefined
        var bar = "derp";
        console.log(bar);       // "derp"
    })
}

Why is that declaration of var bar = "derp" undefining the parameter, that is accessed beforehand? 为什么var bar =“ derp”的声明未定义参数,而该参数是事先访问的?

Because this code 因为这段代码

function foo2(bar) {
    callback(function() {    
       console.log(bar);       // undefined
       var bar = "derp";
       console.log(bar);       // "derp"
    })
}

is actually 实际上是

function foo2(bar) {
    callback(function() {  
       var bar;
       console.log(bar);       // undefined
       bar = "derp";
       console.log(bar);       // "derp"
    })
}

due to the variable hoisting . 由于可变的吊装 So even if you created a global bar variable inside the foo1 call, a scoped variable bar is declared inside the inner scope of the foo2 function. 因此,即使您在foo1调用内部创建了全局bar变量,也将在foo2函数的内部范围内声明有范围的变量bar That's why the first console.log returns undefined 这就是为什么第一个console.log返回undefined的原因

See also Variable hoisting on SO 另请参见SO上的可变提升

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM