Today, mastering JS, I noticed this piece of code:

reader.onload = (function(theFile) { return function(e) { // Render thumbnail. var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" title="', escape(theFile.name), '" src="', e.target.result, '" />'].join(''); document.getElementById('output').insertBefore(span, null); }; })(f); 

Specifically, I was interested in the last line, where, after the parameters of the .onload function, the variable is passed in separate brackets. Please explain why it is needed and how it works, because without it the script is not executed.

  • one
    in this example, in the reader.onload, an expression is assigned that is wrapped in parentheses, which causes it to immediately execute, in turn, the expression returns a function that takes a 1n parameter, and with these mysterious brackets at the end we call this function, passing in it the parameter f - Rostyslav Kuzmovych

1 answer 1

This is a self-invoking function.

The main idea is that an anonymous function is called immediately after its declaration. You will get the advantage of using self-calling functions if you need to run the code once and save its result in the "external environment" (without declaring global variables).

For example, for a small web page, you can write event handlers for elements on the page. Self-calling functions are a suitable means for such a situation.

In this case, the value in brackets is theFile argument.

  • Thank you very much, now I saw it myself - emptybottle
  • It is necessary to transfer the essence of the article by reference directly to the answer. - PashaPash
  • @PashaPash done) - Developer Developer