I do not see how the second solves the closure problem.
This is not true. You still have a close. However, it does not use any private variables.
You can rewrite it to avoid using closure like this:
var clickHandler = function() { this.style.backgroundColor = 'red'; }; function addHandler() { var el = document.getElementById('el'); el.onclick = clickHandler; }
You can also change clickHandler to create with a function declaration instead of a function expression.
clickHandler this should be done with el .
No, it is not. If you used closure, you could use el instead of this .
The value of this determined by how the function is called . Closing in the source code has no purpose. When an event handler runs on an element, this will be the element.
source share