Difference between two functions that execute only once in javascript

0

I searched for a script that did one function only once and found the function below

var something = (function() {
    var executed = false;
    return function () {
        if (!executed) {
            executed = true;
            alert("olá");
        }
    };
})();
<a href="#" onclick="something()">Executar</a>

Well, it works perfectly!

But I did not understand why so much code since I summarized it that way and it works perfectly as well

    var executada = false;
    function chama() {
        if (!executada) {
            executada = true;
            alert("olá");
        }
    };
<a href="#" onclick="chama()">Executar</a>

Any reason specified in the first code?

    
asked by anonymous 06.07.2017 / 12:41

1 answer

10

The reason for these IIFE , in particular in your example, is to create a proper scope block, to have "internal" variables.

Notice that the variable executada in the second example is global, and can be changed without wanting in other parts of the code. While in the first example it is local and can not be modified outside of this IIFE .

In this first example executed gets as a memory type of the function created below with return function () { , and can not be modified from outside IIFE this is very useful.

In addition to the case you mentioned in the example, you can read more examples here (in this answer) . p>     

06.07.2017 / 12:51