Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In JavaScript, functions create new scope. Using a function wrapper around the entire contents of your JavaScript will ensure you never pollute the global scope.</p> <p>For instance, if you have an HTML file with some JavaScript at the bottom:</p> <pre><code>&lt;script&gt; var test = 'hello'; alert(test); //'hello' alert(window.test); //'hello' &lt;/script&gt; </code></pre> <p>As you can see, the <code>test</code> variable actually becomes a property of the <code>window</code> object (<code>window.test</code>), which is essentially JavaScript's global scope. There are many reasons you don't want to set variables on <code>window</code>, particularly future compatibility problems (what if a later version of ECMAScript defines a <code>test</code> property for <code>window</code>?). Also, using global variables all the time is slow, because the interpreter will need to trek all the way up the scope chain whenever you use <code>test</code>.</p> <p>The following is functionally identical to the above, without polluting the global scope. It declares an anonymous function using <code>function()</code>, then invokes it immediately with no arguments using <code>()</code>. This is usually called an immediately-invoked function expression or <strong>IIFE</strong>:</p> <pre><code>&lt;script&gt; (function() { var test = 'hello'; alert(test); //'hello' alert(window.test); //undefined }()); &lt;/script&gt; </code></pre> <p>Note that this is just a normal anonymous function like any anonymous function. The set of parens after the closing curly brace <em>invoke</em> the anonymous function. The parens around the entire thing tell the interpreter that it's looking at a value, or <em>expression</em>, rather than a function declaration. This value is simply the result of the anonymous function when it's run. That makes the anonymous function work like a simple closure which you, the programmer, can effectively ignore.</p> <p>Also, you can use two different syntaxes for IIFEs:</p> <pre><code>(function() {}()); (function() {})(); </code></pre> <p>It's unlikely you'll have problems using either one, but there are <a href="http://nerds.airbnb.com/immediately-invoked-function-expressions-and/" rel="nofollow">some differences</a> that crop up when you've got some syntax problems in your code. IMO you're better off sticking with the first, which is also more clear to read.</p> <p>--</p> <p>As to your second question: <strong>are the following two equivalent?</strong></p> <pre><code>(function(){})(); </code></pre> <p>and</p> <pre><code>function initSomething() {} initSomething(); </code></pre> <p>Errm, wellll, <em>sort of</em>. You could probably get away with treating them the same, because for most purposes they work the same. That is, in your program you will get the same results with either one (in both cases you're defining a function, then calling it).</p> <p>But it's important to note the difference between an anonymous function and a function <em>declaration</em>. You can think of anonymous functions as executables, or blocks of code that you can pass around to work as glue when you don't want to define a real, named function. Because they're anonymous, they don't exist in the scope chain, and you can't, for instance, add properties to an anonymous function object and use them later—unless you assign it to a variable first, in which case it's no longer anonymous!</p> <p>Declaring a function is totally different. It creates a <strong>constructor</strong> that you can use again and again to create new objects (using <code>new</code>) that can inherit the original function's properties. This is useful for many things, particularly when using frameworks like AngularJS.</p> <pre><code>function Friend(likes_you) { //private property, only accessible to instances of this object this.likes_you = likes_you; } //add a function as a property of Friend's prototype - //instances of the Friend constructor can call this function Friend.prototype.greet = function(greeting) { if (this.likes_you) { alert(greeting); } else { alert("I don't like you"); } }; var you = new Friend(true); you.greet('hello!'); //alerts 'hello!' var guy = new Friend(false); //can make as any Friend objects as we want guy.greet('hello!'); //alerts "I don't like you" </code></pre> <p>Of course, you don't need to do anything like this, but it's good to know what JavaScript is <em>really</em> doing. And that's just the start of the JS rabbit hole ...</p>
    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.
    1. COAh, the equivalent of monkey-patching in Python. Nice! Thanks for the explanation. All other answers were good too. But I particularly liked the contrast of constructs in this one. The one thing that I find ironic is that most code I see using this autoexecutable anonymous functions is that they normally have a comment line describing what it is - which is in essence a function name. So, if () creates a scope in Javascript, would this be more readable while still not polluting the global scope? (function initSomething(){})();
      singulars
    2. CO`()` does NOT create scope in javascript. parens are used for grouping code or invoking functions (both of which are being done here). functions create scope. the `()` at the end of the anonymous function *invokes* the function; it does not create scope. It's common to see this sort of wrapper written like `(function() {}());`. This makes it clear that the `()` invokes the function, while the parens around the entire function tell the interpreter that you want to produce a value (i.e. the result of the function after it runs), not declare a function.
      singulars
    3. COyour last question doesn't make sense to me - there's no need to name a function if you only want to use it as a scope wrapper. `(function() {}());` is THE best way to declare an IIFE. Giving the wrapper function a name will add the function as a property of the global `window` object (i.e. polluting the global scope), which is what you're trying to avoid in the first place. So just use the wrapper above and put ALL your code inside the `{}` (or, if you have multiple files, put all the code inside each into a wrapper).
      singulars
 

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