Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Any function in ECMAScript ( core language that JS is based on ) is a separate execution context, and runs individually from one another. Inside of each execution context, <code>this</code> refers to the object in question, defaulting to whatever the function is attached to.</p> <pre><code>function foo() { alert(this===window) } </code></pre> <p>Would alert true, because the window is the object which owns the 'foo' method. Any variables defined in a function become accessed through that function's unique scope chain, environment.</p> <pre><code>function world() { var name = 'global'; alert(name) } </code></pre> <p>would alert 'global' obviously.</p> <pre><code>function world() { var name = 'global'; (function() { var name = 'country'; alert(name) })(); alert(name) } </code></pre> <p>In the latest example, when the first alert is invoked, Javascript determines that in the scope chain of the inner function that the identifier <code>name</code> is defined, so it doesn't have to look up the scope chain to grab it.</p> <p>In the second alert invocation, <code>name</code> is also defined in the same context and alerts 'global';</p> <pre><code>function world() { var name = 'global'; (function() { alert(name) })(); } </code></pre> <p>In this example, the <code>name</code> identifier is not defined in the same context and thus it has to travel up the scope chain to the outer function where name is defined, and it alerts global.</p> <p>Reference:</p> <ul> <li><a href="http://www.digital-web.com/articles/scope_in_javascript/" rel="noreferrer">http://www.digital-web.com/articles/scope_in_javascript/</a></li> <li><a href="http://www.jibbering.com/faq/faq_notes/closures.html" rel="noreferrer">http://www.jibbering.com/faq/faq_notes/closures.html</a></li> </ul>
 

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