Real Useful Javascript Tips
http://code.google.com/p/jslibs/wiki/JavascriptTips
Most of em are pretty straightforward, but certainly almost everyone are pretty advanced.
Some are pretty neat tricks.
I had trouble with this one
closures pitfall
var a = [];
for ( var i=0; i<10; i++ ) {
a[i] = function() { Print(i); }
}
a[0](); // is 10
a[1](); // is 10
a[2](); // is 10
a[3](); // is 10
Var explicitly sets the scope of i inside the for loop. Why then a[0] == 10?
Firebug is a bless for this kind of things :)
When I don't have firebug or any other debugger at hand, this is the most useful construct to find those nasty bugs.
for ( var i in function(){ return [1,2,3] }() )
Print(i)
Or my version
t = "";
for (i in suchvar)
t += i + " = " + suchvar[i] + "\n";
alert(t);
Is there a misprint in your example?
JoC
April 20th, 2007 4:21pm
Maybe just missing info... like what does function() do?
I'm not a java guy.
Since the assignment is coming from function(), I can't really explain why a[0] is anything at all.
I'm just taking your word that a[0-5] = 10.
JoC
April 20th, 2007 5:39pm
Is Javascript. In javascript everything is an object, even functions.
So if you do
a = function(){}
"a" will be an empty function. A little bit like function pointers in C++.
You can even create an array of functions
a = [ function(){return 1}, function(){return 2}]
so
a[0]() will return 1
a[1]() will return 2
Also search for closures. Pretty good stuff :)
Ahh.
So it is because the loop always ends at 10 and wherever you end up evaluating a[x] it is always going to amount to Print(10) once the loop has completed?
JoC
April 20th, 2007 6:16pm
Yeah, something like that.
a[i] is evaluated inside the loop
Print(i) is evaluated when the function executes
My mistake was to think that
for (var i...
Would make i's scope local inside the for loop. That's not the case. I becomes global, so it can be evaluated later.
Also, this is an obligated lecture to understand closures
http://www.jibbering.com/faq/faq_notes/closures.html
You will find those concepts on lisp or in lambda programming (whatever that means :P)
Is there a Javascript compiler? Or cross-compiler into C?
Practical Economist
April 20th, 2007 6:43pm
ultimate js tip: dont use js
iwan
April 21st, 2007 6:16am
Did you get from bed at the wrong side today iwan? Or you didn't get laid last night?
iguess both
iwan
April 21st, 2007 12:51pm
You can always get even with good wake up sex.
Works for me :)
When and where, Masiosare?
iwan
April 22nd, 2007 7:33am