Friday 2 June 2017

JavaScript: Function() constructor: ReferenceError: scope is not defined

I have encounter a probably strange problem. I have a js script named a.js:

var scope = "global";
var f = new Function("return scope");
console.log(f.toString());
f();

When I run nodejs a.js, it complain:

ReferenceError: scope is not defined

But when I run it interactively in nodejs REPL with the command .load a.js, it works correctly.

> .load a.js
> var scope = "global";
undefined
> var f = new Function("return scope");
undefined
> console.log(f.toString());
function anonymous() {
return scope
}
undefined
> f();
'global'

My nodejs version is v4.2.6.
So why the script works interactively, but not as the file option?



via zhenguoli

No comments:

Post a Comment