Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can treat functions as objects and give them "member variables". Here we're using an internal function in <code>fact</code>, but instead of just declaring it as a local variable (<code>var loop = ...</code>), we're putting its definition outside of the function, using object syntax (<code>fact.loop = ...</code>). This lets us essentially "export" the internal <code>loop</code> function of <code>fact</code> so that it can be reused by the function <code>doubleFact</code>.</p> <pre><code>var fact = function(n) { return fact.loop(n, 1); }; fact.loop = function(n, acc) { if (n &lt; 1) { return acc; } else { return fact.loop(n-1, acc * n); } }; var doubleFact = function(x) { return fact.loop(x * 2, 1); }; console.log(fact(5)); // 120 console.log(doubleFact(5)); // 3628800 </code></pre> <p>The same idea could be used to maintain state.</p> <pre><code>var countCalled = function() { console.log("I've been called " + (++countCalled.callCount) + " times."); }; countCalled.callCount = 0; countCalled(); // I've been called 1 times. countCalled(); // I've been called 2 times. countCalled(); // I've been called 3 times. </code></pre> <p>If you want to be able to instantiate multiple ones, each with their own state, try this:</p> <pre><code>var CallCounter = function(name) { var f = function() { console.log(name + " has been called " + (++f.callCount) + " times."); }; f.callCount = 0; return f; }; var foo = CallCounter("foo"); var bar = CallCounter("bar"); foo(); foo(); bar(); foo(); bar(); bar(); bar(); console.log(foo.callCount); console.log(bar.callCount); </code></pre> <p>Outputs:</p> <pre><code>foo has been called 1 times. foo has been called 2 times. bar has been called 1 times. foo has been called 3 times. bar has been called 2 times. bar has been called 3 times. bar has been called 4 times. 3 4 </code></pre>
 

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