【发布时间】:2011-06-26 02:20:24
【问题描述】:
这是一个有趣的范围链案例,在很多文档中都没有解释,我觉得很难理解。如果有人能花时间阅读下面注释良好的代码并解释变量是如何得到解决的,那就太好了
我在一个文档上有两个矩形 (DIV)。我在两者上以及在我注册 mouseup 的 mousedown 侦听器中为 mousedown 注册事件侦听器。 mouseup 的监听器中发生了奇怪的事情。
通过使用不同的参数值两次调用 testfunc 来创建两个执行上下文:
window.onload = function() {
test_func("horizontal"); // First Execution context
test_func("vertical"); // Second Execution Context
}
在第一个矩形(水平)的 mouseup 侦听器中,正在使用第二个执行上下文(垂直),这是反直觉的:
function test_func(dir) {
var X = 9; // variable which helps to track the execution contexts
if(dir === "horizontal")
X = 1; // leave at 9 if vertical
mouseup_vert = function() {}
mouseup_horiz = function() {
// Here the value of X I am getting is 9 whereas I am expecting 11
// QUESTION: Why I am getting the second execution context??
}
mousedown_vert = function() {
// As expected the value of X here is 9
X=99;
// set X to 99 to check if during mouseup same exec context is picked
document.addEventListener("mouseup", mouseup_vert, false);
}
mousedown_horiz = function() {
// As expected value of X is 1, so using first execution context
X=11;
// set this to check if during mouseup I get a value of 11
document.addEventListener("mouseup", mouseup_horiz, false);
}
if (dir === "horizontal") {
e = document.getElementById("horiz");
e.addEventListener("mousedown", mousedown_horiz, false);
} else {
e = document.getElementById("vert");
e.addEventListener("mousedown", mousedown_vert, false);
}
}
【问题讨论】:
标签: javascript scope closures