JQuery, initializing with function

0

I'm in an online course of JQuery where the teacher proposed a code like this:

var inicia = function(){
    var valorTotalItens = $('.valor-total-item');
    var valorBase = 0;
    for (var i = 0; i < valorTotalItens.length; i++) {
        var valorItemTotal = $(valorTotalItens[i]);
        var valorItem = parseFloat(valorItemTotal.text());
        valorBase = valorBase + valorItem;
    }
    $('#quantidade-itens').text(valorTotalItens.length);
    $('#valor-itens').text(valorBase);
}
$(inicia);

However, I wrote the last line before it happened, and I wrote it in another way

inicia();

I wanted to know what the difference was, and why, of my code worked, even after the teacher said it was wrong, and that it should not run.

    
asked by anonymous 02.09.2016 / 03:23

1 answer

2

Without delay, your teacher must have made a mistake in saying that your code would not work. What you did was use something that is very common in JavaScript pure which is to create a Function expression , which is when you assign the address of a function to a variable.

One of the (if not the only) ways of invoking this function without JQuery is just calling this variable with an "open and closed parentheses", and you did just that: inicia(); / p>

What the $(inicia) command does is to use JQuery selector to return a JQuery object. Since your selector is a function, what will happen is that the function will be called and its return will be encapsulated in a JQuery object.

So, every time you use $(inicia) , your function will be executed in the same way that inicia(); occurs in pure JS. The difference is that $(inicia) returns an object JQuery and the inicia(); statement does not.

    
02.09.2016 / 03:42