My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

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


alert(myfunc.name);
// empty string because myfunc
// is a reference of an
// anonymous function


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



function // temporary scope function declaration

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


alert(myotherfunc.name);
// 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)

3 comments:

Anonymous said...

Thank you Andrea! Clear as ever.

Daniel said...

The name property isn't standard. So IE's fine there. Take a look at section 13.2, it's not mentioned once. If you don't trust me, check out the mozilla developer documentation for function properties.

In fact, IE supports the optional identifier for function expressions but Safari doesn't. So IE has better support for the standard than Safari in this case (although this is fixed in the Webkit nightlies).

Andrea Giammarchi said...

You're right Daniel and the fantastic thing is that I personally contributed to write that MDC page (about read-only name informations) ... so I need more memory :D

However, other concepts are the same, even if name is not a standard property.

var f = function(){};
a reference of an anonymous function.

function f(){};
a function called f.

I hope you agree at least about that and thank You for your post :)