Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'this" work in closure?

Tags:

javascript

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.

like image 378
Ghasan غسان Avatar asked Aug 24 '14 10:08

Ghasan غسان


People also ask

How does it work closure?

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.

How does closure work in JS?

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.

What is the benefit of closure?

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.

Why is it called closure?

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.


Video Answer


1 Answers

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.

like image 163
Lucero Avatar answered Oct 19 '22 14:10

Lucero