...

View Full Version : anonymous function in JavaScript



opus1
03-04-2003, 04:59 PM
Where(in what conditions) do you need to use an anonymous function in JavaScript?

beetle
03-04-2003, 05:19 PM
Oop, turns out I have the time after all!

Okay, a quick brief on functions in javascript. Just like strings, arrays, and booleans....functions are variables. Normally, we created them with the function keyword.
function whatever()
{
// code
}However, it's perfectly valid to do this
var whatever = function()
{
// code
}Or, we can use the Function constructor
var whatever = new Function( "// code" );Now, each of these have consumed the variable spaced defined as "whatever".

Now, let me clarify that an anonymous function isn't really anonymous. All functions will take variable space as all the above examples do. It's just that when we apply functions directly to event properties:

1) We are using pre-defined variable space
2) It is rarely the intention to call that function independently

So they have no practical use outside of their intent.

So, let's make a quick example just to alert "Hello World" at the loading of a page.
window.onload = helloWorld;

function helloWorld()
{
alert( "Hello World" );
}Now, based on what I've said so far, you can see that we have given our function an explicit name AND pointed to it (this is called a reference or pointer) with the window.onload event property. Now, let's do it again with a 'anonymous' function
window.onload = function()
{
alert( "Hello World" );
}Now, we didn't consume any extra variable space to achieve the same result.

So, when do we use anonymous functions? I can't honestly think of an application outside of assigning them to event properties. As I said, all those event properties already exist, and have special qualities, that is, they are triggered by events on the page, so assigning a function directly to them saves the middle ground of creating a separate function with separate variable space to do the same job.

I should note that just because you can do event property assigned functions this way, doesn't mean you always should. If ever the same function needs to be used for multiple event properties, a separate function should be made and the event properties should be assigned a pointer to that function, instead.

opus1
03-04-2003, 05:32 PM
Thanks,beetle,for the instant tutorial. WOW!!

I'll take a few moments off to digest it all.

Cheers,
:thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum