Is Javascript Self Executing supposed to work?

I had this code:

function (i) { alert(i); }(3); 

And it didn’t work, so after a StackOverFlow question - I changed it to:

  (function(i){ alert(i); })(3); 

And it works.

I had to () wrap all the code.

But then I saw this code on another site:

 function addLinks () { for (var i=0, link; i<5; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function (num) { return function () { alert(num); }; }(i); // <=== What about this ? there is no () wrapper... so how does it work ? document.body.appendChild(link); } } window.onload = addLinks; 

I wanted to ask , what is the role for part (i) ? Does this do something?

And if it does. Why is it not in the template:

(function(i){ alert(i); })(3);

I mean , where are the wrappers () ?

+4
source share
2 answers

The compiler must distinguish between a function declaration operator and a function definition expression. You can call functions only in expressions.

When the function keyword appears after ' = ' or ( ), the compiler knows that this should be the definition of the function expression (since only expressions, not statements, are allowed after '=' or '(') , and you can call it immediately . When a keyword function launches a new statement, the compiler assumes that it is a declare statement and therefore you cannot call the function immediately .

Note that a function declaration statement requires that you name a function. This allows you to call later. You can omit the function name in function definition expressions (and you can call them right away).

Edited

all bold fonts were made by Roya Namir OP: these bold words are the key to understanding.

 this is the most logical Explanation after a lot of tests. 

See this

http://jsbin.com/imetan/edit#javascript,html

+4
source

Part (i) passes the value of i as a parameter to an anonymous function (a function without a name), which is declared as an onclick event handler, and that’s all. It really does nothing.

Sorry, I'm fixed. (i) performs a function by passing i as a parameter. This leads to the fact that onclick actually such a function:

 function (num) { alert(num); }; 

If you try to access variable i in the same way as from a function, you will always have its final value, in this case 5.

0
source

Source: https://habr.com/ru/post/1379281/


All Articles