1
I have seen some javascript functions with parameters that are not previously defined, but still work. The doubt arose with the function below. The function myFunction()
calls the method pessoas.sort()
, which in turn takes an auto function invoked as argument. It has the parameter a
and the b
. Why does it work even though these haven’t been previously defined? Does the JS engine interpret them by itself? How this can be done at other times and with other parameters?
var pessoas = [
{country:"Brazil", name:"Lucas"},
{country:"EUA", name:"Jhon"},
{country:"Japan", name:"Sushi"}]
function myFunction() {
pessoas.sort(function(a, b){return a.name - b.name});
show();
}
function show() {
document.getElementById("demo").innerHTML =
pessoas[0].country + " " + pessoas[0].name + "<br>" +
pessoas[1].county + " " + pessoas[1].name + "<br>" +
pessoas[2].country + " " + pessoas[2].name;
}
<div id="demo"></div>
<button onclick="myFunction()">Mostrar</button>
Although it is a good question, I think you have a wrong view of self invoked function, none of these of your example are, see: http://answall.com/a/13365/14262
– MarceloBoni
Uhm, you’re right @Marcelobonifazio. I meant that the function that serves as argument of the people method.Sort() is a self invoked function. Thanks for the correction.
– Lucas Trino