Javascript事件处理程序中的范围链

时间:2016-03-23 19:39:05

标签: javascript google-chrome closures

我有一个非常有趣的案例,我无法弄清楚我的闭包概念是否错误,或者Chrome调试器的输出是否出错。

代码在这里https://jsfiddle.net/ygjfutck/ 我已将所有内容都放在HTML中,因为这就是我在本地计算机上复制它的方式。我使用的是Google Chrome v49。

在#button click的事件处理程序中,我正在递增变量a并将结果放在HTML容器中。有趣的是,当我使用Chrome调试工具在事件处理程序回调中放置一个调试点,并在控制台中检查变量b的值时,控制台会抛出一个错误,即变量b未定义。

注意:当我说在控制台中检查b的值时,这意味着打开chrome调试控制台并在那里键入b。这并不意味着使用console.log()或任何其他类似的方法

但是,如果我将事件处理程序更改为此

    $("#button").click(function() {
        a = a + b;
        $selector.html(a);
    });

然后对于相同的调试点,现在将在控制台中定义b。 我不知道在事件处理程序的范围链方面我缺少什么,或者调试器如何查看导致此行为的相同内容。

注意: 如果您无法将调试点放在jsfiddle中,请将HTML复制到本地计算机上的新文件中,然后在Chrome中打开它。

上述小提琴的JS代码

<script>
  function outer() {
    var a;
    var b;
    var $selector;

    var retObj = {
      init: function() {
        a = 10;
        b = 5;
        $selector = $("#id");
        attachEventHandlers();
      }
    };

    function attachEventHandlers() {
      $("#button").click(function() {
        //place a debug point here and then in the console
        //b would not be defined
        //change the below statement to a = a+b, and in the console
        //b would be defined with the correct value
        a = a + 1;
        console.log(a);
        $selector.html(a);
      });
    }

    return retObj;
  }
  var obj = outer();
  obj.init();

</script>

附加了错误的屏幕截图(在JSFiddle外部的单独页面上运行相同的HTML) The error as obtained in the chrome console on explicitly checking the value of b

Just mentioning <code>b</code> inside the event handler in any way, the console would show the correct value

0 个答案:

没有答案