Object-Oriented JavaScript - Second Edition: When using the
Function() constructor, you pass the parameter names first (as
strings) and then the source code for the body of the function (again
as a string). The JavaScript engine needs to evaluate the source code
you pass and create the new function for you. This source code
evaluation suffers from the same drawbacks as the eval() function,
so defining functions using the Function() constructor should be
avoided when possible.
var first = new Function(
'a, b, c, d',
'return arguments;'
);
first(1, 2, 3, 4); // [1, 2, 3, 4]
var second = new Function(
'a, b, c',
'd',
'return arguments;'
);
second(1, 2, 3, 4); // [1, 2, 3, 4]
var third = new Function(
'a',
'b',
'c',
'd',
'return arguments;'
);
third(1, 2, 3, 4); // [1, 2, 3, 4]
Best practice: Do not use the Function() constructor. As with eval()
and setTimeout(), always try to stay away from passing JavaScript code
as a string.
What is the difference? See @Greg's answer