Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' different between REPL and script

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?

like image 215
Maciej Goszczycki Avatar asked Dec 31 '13 17:12

Maciej Goszczycki


People also ask

What does REPL stand for in JavaScript?

js Read-Eval-Print-Loop (REPL) is an interactive shell that processes Node. js expressions. The shell reads JavaScript code the user enters, evaluates the result of interpreting the line of code, prints the result to the user, and loops until the user signals to quit.

Is a shell a REPL?

A shell is not the same as a REPL (Read Evaluate Print Loop). They look similar, but they have deep differences. Shells are designed for one-line commands, and they're a little awkward when used as programming languages.

What is node REPL?

Node. js Read-Eval-Print-Loop (REPL) is an easy-to-use command-line tool, used for processing Node. js expressions. It captures the user's JavaScript code inputs, interprets, and evaluates the result of this code. It displays the result to the screen, and repeats the process till the user quits the shell.


1 Answers

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.

like image 52
cookie monster Avatar answered Oct 05 '22 04:10

cookie monster