Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Lexical closures

by dragonchild (Archbishop)
on Oct 26, 2008 at 00:52 UTC ( #719592=note: print w/ replies, xml ) Need Help??


in reply to Lexical closures

I cannot speak to Python, CLisp, or Scheme, but I can explain why Javascript doesn't behave like Perl. Perl detects when a lexical is being closed over and provides a new scratchpad for each closure. This means that your closure factory does exactly what you intend. In Javascript, a new scratchpad is only provided by a function, not a loop. So, to get the equivalent behavior, you have to do the following:

flist = []; for ( var x = 0; x <= 2; x++ ) { flist.push( make_closure( x ) ); } for ( var f in flist ) { alert( f(2) ); } function make_closure( x ) { return function (v) { x * v } }
This is a common idiom when creating callbacks for event handlers in JS applications. It's bloody annoying and Eichmann has admitted that this is one of the 5 biggest issues to be addressed in JS2.0 (along with namespaces, non-sucky concatenation vs. addition, etc).

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?


Comment on Re: Lexical closures
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://719592]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2014-08-28 01:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (255 votes), past polls