看完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/