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

If you want a new scope in javascript, you can achieve that with an anonymous function that you execute immediately.
// untested! function sayHello(name){ var sayAlert; var newScope = function() { var text = 'Hello' + name; sayAlert = function() { alert(text) } } newScope(); var text = 'How confused am I?'; sayAlert(); }

And that's why you want to program in perl, not in javascript (wherever possible).

  • Comment on Re: "When closures capture their context" and "scope gotchas in Javascript"
  • Download Code

Replies are listed 'Best First'.
Re^2: "When closures capture their context" and "scope gotchas in Javascript"
by clinton (Priest) on Feb 08, 2008 at 16:36 UTC
    Thanks moritz. Actually, I solved my JS problem by just declaring two different variables, instead of reusing the same variable:
    function sayHello(name) { var sayAlert; var text = 'Hello ' + name; sayAlert = function() { alert(text); } var new_text='How confused am I?'; sayAlert(); } sayHello('Bob');

    Not a terribly meaningful example because I don't actually USE new_text, but...

    Perl++ for DWIM!

Re^2: "When closures capture their context" and "scope gotchas in Javascript"
by Jenda (Abbot) on Feb 08, 2008 at 23:25 UTC

    You actually do not need to give the function a name:

    (function(){alert('Gotcha')})();
    or in your case:
    function sayHello(name){ var sayAlert; (function() { var text = 'Hello' + name; sayAlert = function() { alert(text) } })(); var text = 'How confused am I?'; sayAlert(); }