AddEventListener匿名函数中的Javascript变量作用域

Gar*_*een 4 html javascript scope anonymous-function

当点击每个div时,如果单击div 1,它应该警告'1'或如果点击div 2则警告'5'.我试图尽可能地使这些代码变得容易,因为在更大的应用程序中需要这样做.

<html>
<head>
<style type="text/css">
#div1 { background-color: #00ff00; margin: 10px; padding: 10px; }
#div2 { background-color: #0000ff; margin: 10px; padding: 10px; }
</style>
<script type="text/javascript">

function init()
{
  var total = 1;

  var div1 = document.getElementById('div1'),
      div2 = document.getElementById('div2');

  var helper = function(event, id)
  {
      if (event.stopPropagation) event.stopPropagation();
      if (event.preventDefault) event.preventDefault();

      alert('id='+id);
  }

  div1.addEventListener('click', function(event) { helper(event, total); }, false);

  total += 4;

  div2.addEventListener('click', function(event) { helper(event, total); }, false);

}

</script>
</head>

<body onload="init();">

<div id="div1">1</div>
<div id="div2">2</div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!:-)

Mat*_*att 8

问题是事件监听器和'total'都存在于同一范围内(init())

事件函数始终在init()范围内引用total,即使在声明事件函数后更改它也是如此

为了解决这个问题,事件函数需要在自己的范围内具有"总数",这不会改变.您可以使用匿名函数添加另一个范围层

例如:

(function (total) {
    div1.addEventListener('click', function(event) { helper(event, total); }, false);
}(total));

total += 4;

(function (total) {
  div2.addEventListener('click', function(event) { helper(event, total); }, false);
}(total));
Run Code Online (Sandbox Code Playgroud)

匿名函数作为参数传递给init()当前的'total'值.这为匿名函数的范围设置了另一个'total',因此init()的总和是否发生变化并不重要,因为事件函数将首先引用匿名函数的作用域.

编辑:

此外,您需要在辅助函数的右括号后面放置一个分号,否则脚本会抱怨'event'未定义.

var helper = function(event, id)
{
  if (event.stopPropagation) event.stopPropagation();
  if (event.preventDefault) event.preventDefault();

  alert('id='+id);
};
Run Code Online (Sandbox Code Playgroud)

  • @Gary Matt的例子是正确的,这里有一个小术语.由于称为"封闭"(http://www.jibbering.com/faq/faq_notes/closures.html),这是一个强大而强大的JavaScript功能,因此您遇到了特定的问题.Matt告诉你的是如何使用匿名函数和一种称为currying的技术来解决闭包属性(有时会像你看到的那样).请参阅http://ejohn.org/blog/partial-functions-in-javascript/和http://stackoverflow.com/questions/1413916/. (2认同)