gaoxinge gaoxinge - 11 months ago 27
Javascript Question

Is there any mistake in new Function?

I have read the Function. So I try to transform function declaration into function expression by new Function. But, I am stuck in the code below:

function Foo(name, age) { = name;
Foo.prototype.age = age;
var foo = new Foo(1,2); // this is ok

However there is an error after transformation:

var Foo = new Function(['name', 'age'], ';Foo.prototype.age=age;');
var foo = new Foo(1,2); // error: Foo is not defined

Is there any mistake? Any answer is helpful.

The code is right in my chrome browser. However it makes an error on platform:

  • nodejs: 6.10.0

  • win7 64bit

Answer Source

The error is because var Foo isn't defined where the Function can reach it, at least not while using Node.

When you create a function from a string using the new Function() constructor, the function only has access to the global scope, regardless of where it's created.

And, when within a Node module, var Foo and var foo aren't global variables. They're local variables that exists only within the current file/module, within a "module" scope.

var bar = 'bar';
console.log(bar);        // function
console.log(; // undefined

To allow the new Function() to access Foo, you'll have to define the latter as a global variable (or a property of the global object).

global.Foo = new Function(['name', 'age'], ';Foo.prototype.age=age;');
var foo = new Foo(1,2);
// ...

Though, you should be aware that modifying the global scope/object like this is generally frowned upon in Node, since this goes against its intent/design of using isolated modules.

However, to define the function from an expression, you don't need to use the Function constroctor. Rather, you just have to place the declaration where an Expression is expected, such as after an assignment operator.

var Foo = function (name, age) { = name;
    Foo.prototype.age  = age;
var foo = new Foo(1,2); // this is ok
// ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download