Bob5421
Bob5421

Reputation: 9193

node js behaviour for this keyword

Let's have a look to this very basic program.js:

console.log(this);

Here is the output:

$ nodejs program.js 
{}

Now, if i do the samething in the repl console:

$ nodejs 
> console.log(this)

I see a log of things at undefined at the end.

Why do we not get the same result ?

Thanks

Upvotes: 0

Views: 88

Answers (1)

Steven Goodman
Steven Goodman

Reputation: 576

You are experiencing two different behaviors because you're basically executing code in two different environments.

In program.js, this answer applies. You're in a node.js module, so this is the same as module.exports.

In the node.js repl, this answer applies. You're not in a node.js module; you're in the repl which uses the global context. this is the same as global. If you executed the same code in-browser, it'd reference the window object instead of global.

Upvotes: 1

Related Questions