Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Lexical closures

by dragonchild (Archbishop)
on Oct 26, 2008 at 00:52 UTC ( [id://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?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-03-29 15:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found