...

View Full Version : passing a function as an argument



wac
05-04-2004, 10:21 PM
Must one use the function constructor in order to pass a function or can the function name simply be supplied.

eg.

function func1(arg1) { alert 'blah '+arg1 ; }

var func2 = new Function(arg1, "alert 'blah' +arg1;" } ;

function func3(myfunc)
{
myfunc('something') ;
}

can I use
func3(func1) ;

or must I say
func3(func2) ;

liorean
05-04-2004, 10:50 PM
You can use a function declared either through the function declaration, the function expression, or the function constructor. It's all the same to the JavaScript engine.

sad69
05-04-2004, 10:51 PM
I think you can do it either way (at least in IE.. if that means anything!)

This is the code that I used to test:


<html>
<head>
<title>Untitled</title>

<script>
function blah(txt) {
alert(txt);
}

var blee = new Function("txt", "alert(txt);");

function callFn(fn, txt) {
fn(txt);
}
</script>
</head>
<body>

<script>
callFn(blah, "blah");
callFn(blee, "blee");
</script>

</body>
</html>


If someone can verify that this works in other browsers, then it looks good.

Hope that helps,
Sadiq.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum