Node.js: Running a script as file or interactive produces different result

Node.js: Running a script as file or interactive produces different result

Problem

if I save the lines below and run like ./node saved.js

var that = this;
that.val1 = 109;
var f1 = function(){return this;}
var f2 = function(){return this;}
var that1 = f1();
var that2 = f2();
console.log(that1.val1)//undefined
that1.val2=111;
console.log(that2.val2)//111

I get this result

undefined
111

But if I paste it to already started shell ./node, I get

...
...
> console.log(that1.val1)//undefined
109
undefined
> that1.val2=111;
111
> console.log(that2.val2)//111
111 

Why is the output of the first console.log different?

Problem courtesy of: mert inan

Solution

When you run it in the script, this inside of your functions refers to a different object than it does outside your functions. For example, I made this change to the beginning of your script:

var that = this;
console.log(this)
that.val1 = 109;
var f1 = function(){console.log(this); console.log("eq: " + (this === that));return this;}

When that second line executes running it as node test.js, I get an empty object, whereas then the one inside of f1 is executed a few lines deeper, it’s a much different object.

When that’s run from the Node REPL, I get an object matching the one from inside f1 in the node test.js version in both places. Thus, that.va1 = 109 is acting on different objects in the 2 cases and is why you see the difference.

Edit: And see Jonathan Lonowski’s comment on the question for what the 2 different objects are.

Solution courtesy of: juanpaco

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *