Function Declaration in JavaScript

It is easy to declare a function in JavaScript. And everyone knows it:

Standard or Procedural Function

; function func()
{
...
}

The problem of it is this function cannot be passed as parameter in another function. To be able to do that, you will need to varibalize it:

Varibalized Function, or Function Literal, Function Reference, Function Pointer

; var func = function()
{
...
}

Everyone does that too. Wait a moment. This form for declaration indeed is just set to fail if you use it carelessly. You may get following error massage when sequence to execute programming block becoming sensitive, such as work with setTimeout() and setInvertal() or inside of a function:

[This function] is not defined.

If you include this form of function with setInterval or setTimeout, you may get error message:

useless setInterval call (missing quotes around argument?)

This is because you will need to put it in right sequence to make sure the memory has load the function first.

So, it is suggested in general you should use orthodox function declaration method. If you use variablized function declaration method, please make sure it has been put into right place in the sequence of programming blocks.

Have a look at following case:

; var func = func()

; function func()
{
...
}

No, this is not a function declaration method for first statement. It just get the return value from the function func().

Apart from above mentioned popular method, here is

Function Object

; var func = new Function()
{
...
}

It is not recommended to use because it would take longer time to process, unless for special purpose, such as reconstruct to function from variablized function and variablized parameters. For instance:

; var reconstructedVar = new Function([para1, para2,...paran], functionBody)
{
...
}

Please take note, all parameters and function body must be in string or reference. The other way to reconstruct the function is to do it by yourself. For details, please see Passing Function in JavaScript.


http://www.permadi.com/tutorial/jsFunc/index.html
http://www.hunlock.com/blogs/Functional_Javascript
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
http://osdir.com/ml/jQuery/2009-11/msg01942.html
Javascript Error Message: is not a function

1 comment:

  1. http://www.hunlock.com/blogs/Functional_Javascript

    ReplyDelete

Labels