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:
- Does it work?
- Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|