Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2015-12-01 13:54 GMT
Find Nodes?
    Voting Booth?

    My keyboard shows this many letters:

    Results (12 votes), past polls