'this' different between REPL and script

笑着哭i 提交于 2020-01-26 08:11:16

问题


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?


回答1:


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.




回答2:


When you use node to run script from a file, it implicitly sets it up as a module with its own scope.

When you just run it without a file, you're dropped into the REPL but not in any module scope.



来源:https://stackoverflow.com/questions/20861049/this-different-between-repl-and-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!