Passing Function in JavaScript

To pass function like a reference, one needs first to make the function a variable reference:

; var funcationName = function(argu) { ... }

Then, it can be passed:

; function anotherFunc(passingFunc)
{
; passingFunc(para)
}

Use it just like the function itself. Indeed, if there is no parameter for functionName(), you will still need to use it as function:

; function anotherFunc(passingFunc)
{
; passingFunc()
}

Function passing even can be used to across the html pages, just like variable reference passing:

; function anotherFunc(passingFunc)
{
; parent.passingFunc()
}

In HTML, following syntax is used to invoke the function:

onkeypress="anotherFunc(funcationName)"

It is very important, the sign of () could NOT be put in invokin statement in HTML, something like:

onkeypress="anotherFunc(funcationName())"

Now, this syntax does create confusion when you want to pass the parameter as will, for instance, you want to call anotherFunc(funcationName(argu)). The ways to overcome it is:

1. For static passing function with dynamic passing varialbe: Declare argu as global variable. Codes are as follows:

; var para

; var funcationName = function(argu) { ... }

; function anotherFunc(passingFunc)
{
; passingFunc(para)
}

onkeypress="para=something;anotherFunc(funcationName)"

3. If you want a complete dynamic passing function together with a dynamic passing variable, you will need to create third function:

; var para

; var funcationName = function(argu) { ... }

; var thirdFunc = function()
{
...
; funcationName(para)
...
}

; function anotherFunc(passingFunc)
{
; passingFunc()
}

onkeypress="para=something;anotherFunc(thirdFunc)"

Function thirdFunc() indeed is where you should play with.

Another approach is to write a function to reconstruct the function from variables:

; function reconstructFunc(func, totalPara, para1, para2, para3)
{
; var newFunc
; if (0==totalPara) newFunc = func
else if (1==totalPara)
{
; newFunc = function()
{
; func(para1)
}
}
else if (2==totalPara)
{
; newFunc = function()
{
; func(para1, para2)
}
}
else
{
; newFunc = function()
{
; func(para1, para2, para3)
}
}
; return newFunc
}

It is very important when passing function, the function must be properly declared. Please refer to http://koncordpartners.blogspot.com/2010/04/function-declaration-in-javascript.html. This article also covers another method to reconstruct the function from variablized function and parameters.

If the function reference/literal had passed across HTML pages, in IE 8 it might general error as "Function expected". To overcome this, you need to set up a local variablized function to call access remote function.

No comments:

Post a Comment

Labels