REPL 和脚本之间的“这个"不同 [英] 'this' different between REPL and script
问题描述
在通读 mozilla 文档后我发现这个:
After reading through mozilla docs I found this:
在全局执行上下文中(在任何函数之外),this 指的是全局对象,无论是否处于严格模式.
In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.
在玩了一会儿范围之后,我发现在 node.js REPL 中...
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
这是有原因的吗?还是bug?
Is there a reason for this? Or is it a bug?
推荐答案
Node 的 REPL
是全局的.来自文件的代码位于模块"中,它实际上只是一个函数.
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);
注意它是使用 .call()
执行的,并且 this
值被设置为一个预定义的对象.
Notice that it's executed using .call()
, and the this
value is set to a pre-defined object.
这篇关于REPL 和脚本之间的“这个"不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!