Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is indeed a major difference between C/C++ and JavaScript: JavaScript is a reference-counted, garbage-collected language, which means that objects can be reclaimed by the engine when they no longer have any references to them. The function you assign to <code>printColor</code> isn't on the stack, per se, as it would be in C or C++; it's allocated dynamically and then assigned to a variable outside your current scope. So, when control flow returns from <code>changeColor</code>, the anonymous function still has a reference count of <strong>1</strong> since the outer <code>printColor</code> refers to it, and thus it's usable from the outer scope.</p> <p>So, your example isn't so much of a scoping issue--it's clear that you declare <code>printColor</code> <em>outside</em> of the function scope of <code>changeColor</code>. When you define <code>changeColor</code>, it <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="nofollow">closes</a> the upvalue <code>printColor</code> into the new function scope, making it accessible. Like <strong>Combat</strong> said, if you add a <code>var</code> to the second, inner definition of <code>printColor</code>, it'll <a href="http://en.wikipedia.org/wiki/Variable_shadowing" rel="nofollow"><em>shadow</em></a> the first <code>printColor</code> you declared and it won't be accessible outside that function block.</p> <p>As far as other issues to be aware of, yes, there are quite a few, but see my comment on your original post for a good start.</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