4

Can someone help me understand the following behavior? I'd expect that, since I can set the global f from inside this callback, I should also be able to change it. I don't understand well enough how node handles context vs. global in the REPL to make sense of this, and I'd appreciate any insight.

Start a REPL without useGlobal

$ cat test.js 
var repl = require('repl');
repl.start({useGlobal:false});

Now try setting f twice in a row:

$ node test.js 
> f
ReferenceError: f is not defined
>  setTimeout(function(){f=1;}, 0);
> f
1

Works the first time... now try again:

>  setTimeout(function(){f=2;}, 0);
> f
1

Huh!

The first run sets it; the second doesn't affect it.

(Setting useGlobal:true I get the behavior I expect.)

4
  • just a note: the problem exists also with a delay > 0, and NOT exists with anonymous functions: !function() { f = 2}(); works as expected. I've no Idea... maybe a bug? Commented Sep 20, 2012 at 19:10
  • I think that "this" developer.mozilla.org/en-US/docs/DOM/… has some effects on "this" problem :) Commented Sep 20, 2012 at 20:21
  • @chumkiu The keyword "this" is not used in the code. Why should it be responsible for the above problem? Commented Oct 3, 2012 at 12:18
  • @Javaguru yes but the option useGlobal if set to true , then the repl will use the global object, instead of running scripts in a separate context. I suppose it has something to do with this (maybe for a low-level bug) Commented Oct 3, 2012 at 13:37

2 Answers 2

2

It's because of Node's faulty vim module which is what's running your code behind the scenes. When you disable useGlobal this changes the manner in which it runs your code, changing from vm.runInThisContext to vm.runInContext [1]. Essentially what happens is that it copies all the variables from the specified sandbox object over to the actual global object it runs your code in, executes the code, then copies everything back. When you use setTimeout the change is made after everything is copied back. The blame for this lies partially in the repl module [2] and partially in the vm module [3]. I believe the vm module is slated for an overhaul for the next version.

Sign up to request clarification or add additional context in comments.

Comments

-1

Try typing .clear into the console. It updated the global values for me.

The following line wasn't working for me from the selected answer. repl.start('>',{useGlobal: true});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.