Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Declaring the variable outside the function makes the function use the same object every time.</p> <p>An example (with an integer instead of an object, for simplicity's sake):</p> <pre><code>var c = { theMethod: function () { var m1 = 0; return function (theParameter) { m1++; console.log( m1 ); } }() }; c.theMethod(); c.theMethod(); // output: 1 2 var d = { theMethod: function () { return function (theParameter) { var m1 = 0; m1++; console.log( m1 ); } }() }; d.theMethod(); d.theMethod(); // output: 1 1 </code></pre> <p>The self-invoking function works like this:</p> <pre><code>var c = { theMethod: function () { var m1 = 0; return function (theParameter) { m1++; console.log( m1 ); } }() }; </code></pre> <p>When the object <code>c</code> is created, the self-invoking function invokes itself and <code>theMethod</code> now equals the return value of that function. In this case the return value is another function.</p> <pre><code>c.theMethod = function( theParameter ) { m1++; console.log( m1 ); }; </code></pre> <p>The variable <code>m1</code> is available to the function because it was in scope when the function was defined.</p> <p>From now on when you call <code>c.theMethod()</code> you are always executing the inner function that was returned from the self-invoking function, which itself executed only once at the time the object was declared.</p> <p>The self-invoking function works just like any function. Consider:</p> <pre><code>var c = { theMethod: parseInt( someVariable, 10 ) }; </code></pre> <p>You don't expect <code>parseInt()</code> to execute every time you use the <code>c.theMethod</code> variable. Replace <code>parseInt</code> with an anonymous function as in the original and it's exactly the same thing.</p>
 

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