Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"Best" is an inherently subjective thing, but I'll try to point out some information about each and let you make up your own mind about "best."</p> <h3>Example 1</h3> <p>...gives you a handy scope (the anonymous function) where you can put truly private class-wide information (and utility functions) which only the <code>Class</code> functions have access to:</p> <pre><code>var Class = (function(){ var trulyPrivateInformation = 42; function trulyPrivateUtilityFunction() { // ... } function Class() { this.test = 'test' } return Class; })(); </code></pre> <p>Example 1 is not "hoisted." It is processed as part of the step-by-step code.</p> <p>The <code>Class</code> function will have a real name.</p> <h3>Example 2</h3> <p>...creates a function that has no name and assigns it to a variable that has a name. Modern browsers are pretty smart about it, but in theory at least, the function is anonymous, which impacts what information your tools can provide you. It also doesn't have the private class-wide scope Example 1 has.</p> <p>Like Example 1, Example 2 is processed as part of the step-by-step code, not hoisted.</p> <h3>Example 3</h3> <p>...is just Example 1 without the private class-wide scope, but it's also "hoisted"&nbsp;&mdash; the <code>Class</code> function is defined before <strong>any</strong> step-by-step code is executed. That means this works:</p> <pre><code>var c = new Class(); console.log(c.test); // Logs 'test' function Class() { this.test = 'test'; } </code></pre> <p>Note that even though <code>Class</code> is defined lower down, it's done <em>before</em> the code above runs. This isn't true of either Example 1 or Example 2.</p> <p>As with Example 1 (but not 2), the <code>Class</code> function has a real name.</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