About (function () {...} ()) and callThis ()

13

CoffeeScript compiles your files into one:

(function(){
  // código aqui
}()).callThis();

JSFiddle: link

Sometimes we find a variation on the internet:

(function(){
  // código aqui
}());

JSFiddle: link

What is the use of this?

    
asked by anonymous 08.07.2014 / 13:30

1 answer

14

The main utility of these IIFE (immediately auto-invoked function) is to create a closure for variables. Thus all the variables defined within this enclosure are not exported to the global space, and therefore do not pollute it.

This functionality has to do with the normal functioning of functions and how they create / change the scope of the code. What's different here is that it is immediately invoked / running and does not wait to be called.

The other important reason is that the created variables stay within that scope and are freed from memory after the run function, passing its value out if necessary (see example 2 below).

Some practical examples of this application:

Example 1:

(function(global){
  // código aqui
})(this);

In this example we pass into the function the this of global space. In the case of javascript on the client side this will be window but in the case of Node.JS this will be global .

Example 2:

// #2479 - IE8 Cannot set HTML of style element
var canChangeStyleHtml = (function(){
    var div = document.createElement('style'),
        flag = false;
    try {
        div.innerHTML = '#justTesing{margin: 0px;}';
        flag = !!div.innerHTML;
    } catch(e){}
    return flag;
})();

This example above made for the MooTools library to know if the browser in which the code is run can change the HTML of a <style> element. In this way the function runs (auto-invoked) returns true or false . So I have this information stored and I can use it in the rest of my code, and I do not need to run this function anymore.

Example 3:

var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
    (function () {
        var numero = Math.round(Math.random() * 20);
        buttons[i].addEventListener('click', function () {
            alert(numero);
        });
    })();
}

This example shows a for cycle in which each iteration runs an IIFE. This function creates its own scope that is passed and saved. So each time you click a button it will have in memory the value that corresponds to it, without being rewritten. Example online: link , and already the same example without IIFE: link - all buttons have the same value.

    
08.07.2014 / 13:54