Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In your specific case there is no difference (note that the function in your first fragment is invoked with the parameter <code>file</code>, but since you ignore it it shouldn't have any side effects). However, have a look at the following example:</p> <pre><code>var reader = new FileReader(); var my_temporary_var = 42; reader.onload = function(e){ loadData(e.target.result, my_temporary_var); } </code></pre> <p>So far everything is the same. But if you change <code>my_temporary_var</code> it will also be changed <em>inside</em> of your anonymous function. To prevent this you create a closure:</p> <pre><code>reader.onload = (function(some_value) { return function(e){ loadData(e.target.result, some_value); }; })(my_temporary_var); </code></pre> <p>You create an anonymous function which takes the argument you want to bind to another function and then call this function immediately. Note that the dependency on <code>my_temporary_var</code> has been resolved.</p> <h3>Other example</h3> <p>Some people like to create many functions in a for-loop:</p> <pre><code>var i; for(i = 0; i &lt; myObjects.length; ++i) myObjects[i].onload = function(e) { myObjects[i].doSomething(); }; </code></pre> <p>Lets assume that <code>myObjects[0].onload</code> will be handled first, but <em>after</em> the for loop. The given handler <code>function(e) { myObjects[i].doSomething(); };</code> uses the object <code>myObjects[i]</code>. However, <code>i == myObjects.length</code>: we access an object which isn't even there! And since we try to access an attribute of that function, we'll get an exception and the script will stop.</p> <p>This happened because <code>i</code> in the anonymous function is a reference, and not used as a value. In order to prevent this you must use a closure:</p> <pre><code>var i; for(i = 0; i &lt; myObjects.length; ++i) myObjects[i].onload = (function(index){ return function(e) { myObjects[index].doSomething(); }; })(i); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload