Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

'this' different between REPL and script

Tags: repl script code

'this' different between REPL and script

Problem

After reading through mozilla docs I found this:

In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.

After playing with scopes for a little I found that in node.js REPL...

> this === global
true

but when I create a Script with the same line...

$ cat > script.js
console.log(this === global)
$ node script.js
false

Is there a reason for this? Or is it a bug?

Problem courtesy of: mgoszcz2

Solution

Node's REPL is global. Code from a file is in a "module", which is really just a function.

Your code file turns into something like this very simplified example:

var ctx = {};
(function(exports) {
    // your code
    console.log(this === global);
}).call(ctx, ctx);

Notice that it's executed using .call(), and the this value is set to a pre-defined object.

Solution courtesy of: cookie monster

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

'this' different between REPL and script

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×