I had this idea that, as soon as you made a closure, all the variables were neatly packaged up and were immutable outside of the closure itself. Then I saw some weird behaviour in Javascript, and investigated further.

Turns out that my assumption was just plain wrong. For instance:

test.pl: ---------------------------------------------- sub say_hello { my $name = shift; my $text = 'Hello '.$name; my $sayAlert = sub { print "$text\n" }; $text = "Not in Perl you don't"; $sayAlert->(); } say_hello('Bob'); ---------------------------------------------- > perl test.pl Not in Perl you don't
Now, reading that again, it makes sense that I would still have access to the variable in the closure from the same scope in which it was declared. So understandably, this version will work as I originally expected:
test.pl: ---------------------------------------------- sub say_hello { my $name = shift; my $sayAlert; { my $text = 'Hello '.$name; $sayAlert = sub { print "$text\n" }; } my $text = "Not in Perl you don't"; $sayAlert->(); } say_hello('Bob'); ---------------------------------------------- > perl test.pl Hello Bob

However, try the same thing in Javascript, and it doesn't work:

function sayHello(name) { var sayAlert; { var text = 'Hello ' + name; sayAlert = function() { alert(text); } } var text='How confused am I?'; sayAlert(); } sayHello('Bob'); ---> "How confused am I?"

It turns out that, unlike Perl, creating a new (nested) block in JS does NOT create a new scope. Instead a new scope is created when a function is declared. Oh, and it doesn't give you any "variable text redefined" warnings either.


In reply to "When closures capture their context" and "scope gotchas in Javascript" by clinton

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.