Reputation: 116283
JavaScript has a Function
constructor which produces an anonymous function:
new Function()
When passing a function as an argument to Function
, I get a syntax error:
new Function(function(){})
produces
SyntaxError: Unexpected token (
However, when I pass a number, all is fine:
new Function(10)
Why do I get a syntax error when passing a function to Function
?
Upvotes: 0
Views: 132
Reputation: 309
I would suggest using:
new Function(func)
instead of
new Function(func(){})
where you have to define func as a separate function. The following example demonstrates:
<html>
<script>
function init(func)
{
func();
}
function greet()
{
alert("good morning!");
}
</script>
<body onLoad="init(greet);">
<body>
</html>
Upvotes: 0
Reputation: 4237
I don't know way that error, but you can try something like this:
var func = function(){};
new Function(func)
Upvotes: 0
Reputation: 16841
Because the Function constructor expects String arguments and evaluates the last one to be the function body, expecting it to be valid javascript. When it attempts to evaluate the anonymous function argument as a String, it fails, because the String representation of that anonymous function is not valid javascript.
Upvotes: 2
Reputation: 33447
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function
Considering all but the last arguments are argument names, I wouldn't expect anything other than a string to work.
I would imagine the syntax error is because of the way the JS engine you're using internally tries to convert the function to a string. I'm actually surprised it doesn't choke on the 10.
Also, I suspect you're doing this just out of curiosity, but if you're not, I suggest you not use Function
in code you can control. There's not really a reason to use Function unless you need to take a string and make a function out of it at run time.
Upvotes: 2