Jquery, Initiating with Function

Asked

Viewed 148 times

0

I’m in an online Jquery course 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 passed, and wrote otherwise

inicia();

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

1 answer

2


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

One of the ways (if not the only one) to invoke this function without JQuery is just calling this variable with a "opens and closes parentheses", and you did just that: inicia(); It’s very common that.

What do I command $(inicia) makes use of the JQuery selector to return an object JQuery. As his selector is a function, what will occur is that the function will be called and its return will be encapsulated in a Jquery object.

Therefore, each time you use $(inicia), its function will be performed in the same way as inicia(); occurs in pure JS. The difference is that the $(inicia) returns an object JQuery and the instruction inicia(); nay.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.