javascript - REPL和脚本之间的'this'不同

标签 javascript node.js this global

看完mozilla docs我发现了这个:

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

在玩了一会儿范围之后,我发现在 node.js REPL...

> this === global
true

但是当我用同一行创建脚本时...

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

这是有原因的吗?还是bug?

最佳答案

Node 的 REPL 是全局的。文件中的代码位于“模块”中,实际上只是一个函数。

你的代码文件变成了这样一个非常简化的例子:

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

请注意,它是使用 .call() 执行的,并且 this 值设置为预定义的对象。

关于javascript - REPL和脚本之间的'this'不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20861049/

相关文章:

javascript - 从选定的记录设置下拉列表的值

java - 在开发网络客户端应用程序时,你能推荐开发集成工具吗?

javascript - 使用带有字符串和 bool 值的对象创建 Json 列表

jquery - 该对象 "undefined"

Java将变量从父类(super class)传递到子类

javascript - 如何使用 Jquery 阻止浏览器调用 Digest auth 弹出窗口并处理 401 错误?

javascript - DynamoDB 扫描返回多个扫描结果

javascript - 使用 new 和存储在变量中的 ES6 类的 Node 出现错误

node.js - Node.js 中的 Hashmap 模块?

javascript - 如何通过 ng-click 将其传递给 Angular 函数?