JavaDeveloper
JavaDeveloper

Reputation: 5660

How to make a string converted function return value in javascript

fnOriginal = function(){
  console.log("hello");
  return 10;
};

var fun = new Function("fnOriginal()");
console.log(fun()); // prints undefined.

console.log(fnOriginal()); // prints 10

How would I make fun() return and print 10 like fnOriginal()?

Upvotes: 1

Views: 68

Answers (2)

Sharad
Sharad

Reputation: 743

Use following

fnOriginal = function(){
  console.log("hello");
  return 10;
};

var fun = new Function("return fnOriginal();");
alert(fun());

It will return 10.

Upvotes: 0

georg
georg

Reputation: 214959

Obviously,

var fun = new Function("return fnOriginal()");

new Function("code") is the same as function() { code }. If the code's missing a return statement, the function won't return anything.

Upvotes: 2

Related Questions