Javascript variable scope in addEventListener anonymous function

扶醉桌前 提交于 2019-12-03 16:44:41

The problem is that the event listeners and 'total' both exist in the same scope (init())

The event functions are always going to reference total within the init() scope, even if it is changed after the event functions are declared

To get around this, the event functions need to have a 'total' in their own scope which will not change. You can add another layer of scope using an anonymous function

For example:

(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));

The anonymous functions are passed init()'s current 'total' value as a parameter. This sets another 'total' to the anonymous function's scope, so it does not matter if init()'s total changes or not, because the event function will FIRST reference the anonymous function's scope.

Edit:

Also, you need to place a semicolon after the closing brace of the helper function, otherwise the script will complain that 'event' is undefined.

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

  alert('id='+id);
};
m4roo

This is almost the same but i think it will be better:

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

instead of:

(function (total) {
    div2.addEventListener('click', function(event) { helper(event, total); }, false);
}(total));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!