Are these two functions doing the same thing behind the scenes? (in single statement functions)
var evaluate = function(string) {
return eval(\'(\' + str
new Function
creates a function that can be reused. eval
just executes the given string and returns the result of the last statement. Your question is misguided as you attempted to create a wrapper function that uses Function to emulate an eval.
Is it true that they share some code behind the curtains? Yes, very likely. Exactly the same code? No, certainly.
For fun, here's my own imperfect implementation using eval to create a function. Hope it sheds some light into the difference!
function makeFunction() {
var params = [];
for (var i = 0; i < arguments.length - 1; i++) {
params.push(arguments[i]);
}
var code = arguments[arguments.length - 1];
// Creates the anonymous function to be returned
// The following line doesn't work in IE
// return eval('(function (' + params.join(',')+ '){' + code + '})');
// This does though
return eval('[function (' + params.join(',')+ '){' + code + '}][0]');
}
The biggest difference between this and new Function is that Function is not lexically scoped. So it wouldn't have access to closure variables and mine would.