Ixx*_*Ixx 4 javascript variables jquery closures
我有这样的功能:
function foo(canvas) {
canvas.mousedown(function(e) {
console.log(canvas); //undefined
});
}
Run Code Online (Sandbox Code Playgroud)
我在页面的某个位置点击鼠标来调用foo.
为什么画布未定义?
Cha*_*lie 11
在使用之前,调试器可能不会在闭包中显示变量.
考虑这个示例,其中定义了一个变量但从未使用过:
(function() {
var x = 1;
$(function () {
debugger; // debugger stopped here, `x` is `undefined` in Chrome and IE but `1` in Firefox
console.log("hi");
}
})();
Run Code Online (Sandbox Code Playgroud)
打印出变量以外的相同代码而不是字符串文字:
(function() {
var x = 1;
$(function () {
debugger; // debugger stopped here, all three browsers show `x` as `1`
console.log(x);
}
})();
Run Code Online (Sandbox Code Playgroud)
问题是这样的:
function foo(canvas) {
canvas.mousedown(function(e) {
console.log(canvas); //undefined
//...
for (var i in array) {
var canvas = array[i].canvas;
//...
}
});
}
Run Code Online (Sandbox Code Playgroud)
我没有时间去调查具体原因。我的猜测是编译器在匿名函数的开头放置了一个“var canvas”声明,这样在控制台中输出时该变量是未定义的。不然还没明白。