Javascript执行上下文,鼠标处理程序内的反直觉范围链

时间:2011-02-12 14:15:01

标签: javascript scope closures

这是一个有趣的范围链案例,在很多文档中没有解释,我发现很难理解。如果有人可以花时间阅读下面评论良好的代码并解释变量如何解决,那将是非常好的

我在文档上有两个矩形(DIV)。我在mousedown监听器中注册了mousedown的事件监听器,我注册了mouseup。在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);
    }            
}

1 个答案:

答案 0 :(得分:6)

这是因为引用函数的变量不是用var声明的,所以它们是全局的。

他们被第二个电话覆盖,第二个电话以价值X 9左右结束。


编辑: 以下是有效发生的事情。为简单起见,我将所有变量都放在相同的范围内。

   // "a" is referencing a function.
var a = function() { alert( 'a' ); };

   // "b" is referencing the same function that "a" is referencing.
var b = a;

   // The reference "a" holds to the function is being overwritten with a 
   //     reference to a new function.
a = function() { alert( "I'm a new function" ); };

   // "c" is referencing the same function that "a" is referencing (the new one).
var c = a;

   // So what is "b" referencing? It is still the original function, because it
   //    picked up that reference *before* the original reference "a" held was
   //    overwritten.

b(); // alerts 'a'

...或者让代码更具体一些代码:

  // reference a function
var mouseup_vert = function() { alert( "I'm a mouseup function." ); };


  // reference a function
var mousedown_vert = function() {
                    // When this function is invoked, add a listener using
                    //    whatever function is referenced by mouseup_vert
                 document.addEventListener( "mouseup", mouseup_vert, false);
};


  // The function currently referenced by "mousedown_vert" is passed here
  //    as the event handler.
document.addEventListener("mousedown", mousedown_vert, false);


  // Overwrite "mouseup_vert" just for kicks.
mouseup_vert = function() { alert( "I'm a completely different function." ); };


  // NOW trigger a "mousedown" event. What happens? The function passed as the
  //    handler is invoked. 

  // What does that function do? It adds a "mouseup" handler. 

  // Which variable is referenced? "mouseup_vert".

  // What is the current value of "mouseup_vert"? The new function, since we
  //    overwrote the reference to the original.