2

I have below piece of code in test.js file

   function foo(){
      console.log(this.bar);
    }

    var bar = "bar1";
    var obj = {bar: "bar2"};

    foo();
    foo.call(obj);

when I run by 'node test.js', I got result

undefined 
bar2

when I run in node .editor, I got result

bar1 
bar2

I think the second result is right, but what is wrong with the first way? cuz I always do the first way.

what are the differences between them?

3
  • What did you meant by node .editor, is it REPL mode? Commented Sep 15, 2018 at 3:54
  • yes, in REPL, type '.editor' Commented Sep 15, 2018 at 3:56
  • Here is your answer, stackoverflow.com/questions/34967530/… Commented Sep 15, 2018 at 4:06

2 Answers 2

1

In simple terms when you run the your code using node test.js, Node JS will require('test.js') to run it. But when you are using the REPL mode, code you enter will execute directly in the REPL.

When using require, the variables on your test.js won't bind as global variables. So cannot access like this.bar

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

Comments

0

I think when using 'node test.js', node create a wrapper for test.js code, so there is no global variable bar.

while in .edit way, there is a variable bar defined in global scope.

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.