Saturday 11 March 2017

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) {
    Foo.prototype.name = name;
    Foo.prototype.age  = age;
}
var foo = new Foo(1,2); // this is ok
console.log(Foo.prototype.hasOwnProperty('name'));
console.log(foo.hasOwnProperty('name'));

However there is an error after transformation:

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

Is there any mistake? Any answer is helpful. Thank you.

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

  • nodejs: 6.10.0
  • win7 64bit


via gaoxinge

No comments:

Post a Comment