I got to this document which says there is a closure happening here:
function addHandler(){
document.getElementById('el').onclick = function(){
this.style.backgroundColor = 'red';
};
}
While this code removes the closure:
function addHandler() {
var clickHandler = function() {
this.style.backgroundColor = 'red';
};
(function() {
var el = document.getElementById('el');
el.onclick = clickHandler;
})();
}
I can't see how the second one solves the closure issue. Why would not the code at el.onclick = clickHandler
create a closure? clickHandler
's this
has to be fulfilled with el
.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.
Advantages of closuresThey allow you to attach variables to an execution context. Variables in closures can help you maintain a state that you can use later. They provide data encapsulation. They help remove redundant code.
The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.
Your example is not correct. The document you have linked to states that this code block creates a closure which may leak memory (note the variable in the outer function):
function addHandler() {
var el = document.getElementById('el');
el.onclick = function() {
this.style.backgroundColor = 'red';
};
}
Both examples you posted do not create a closure (or only an empty one), but they use different means to avoid it.
Also note that this problem seems to affect IE's JS engine only. Other engines, auch as V8 / Chrome, seem to only capture the variables used in inner functions in closures, so that I'd expect that no circular reference would be created in this code example, and even if it would they should be able to handle the garbage collection with the circular reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With