Tuesday, March 13, 2007

function or var function ? part #2

I did an error talking about difference using function, var function and (function), because as Matteo said in my last post I didn't explain perfeclty the difference from an anonymous function and a simple reference variable.

Here You can view an example, probably better than every word:

var // temporary scope variable declaration

myfunc // variable name (as function referer)


function(){}; // anonymous function

// empty string because myfunc
// is a reference of an
// anonymous function

// ---------------------------- //

function // temporary scope function declaration

myotherfunc(){};// "the" myotherfunc function

// string "myotherfunc" because
// myotherfunc is not a reference
// but exactly a function

So, an anonymous function has some limit, as I said on my old post but if You need a simple, tiny function that you're not using as class, You could declare anonymous function even inside a for loop

for(var f = function(){}, a = [1,2,3], b = a.length; b > 0; b--)
// do stuff

but if You need a class or a more complex function I suggest to use the "old classic" way:

function f(){
// do stuff

That's all, You should remember that first example doesn't work, obviously, on Explorer, try them with other standard compilant browser (FireFox, Opera, Safari, Konqueror ... etc)

No comments:

Post a Comment