$(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"
})
}
为什么 var bar = "derp"的声明取消了预先访问的参数的定义?
最佳答案
因为这段代码
function foo2(bar) {
callback(function() {
console.log(bar); // undefined
var bar = "derp";
console.log(bar); // "derp"
})
}
实际上是
function foo2(bar) {
callback(function() {
var bar;
console.log(bar); // undefined
bar = "derp";
console.log(bar); // "derp"
})
}
由于变量提升。因此,即使您在 foo1
调用中创建了全局 bar
变量,也会在 的内部范围内声明一个作用域变量
函数。这就是为什么第一个 bar
foo2console.log
返回 undefined
另见 Variable hoisting就这样
关于javascript - 为什么在回调中声明一个 var 会取消定义参数? (吊装),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29791771/