REPL和脚本之间的'this'不同 [英] 'this' different between REPL and script
问题描述
阅读 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 ...
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?
推荐答案
节点的 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()
,此
值设置为预定义对象。
Notice that it's executed using .call()
, and the this
value is set to a pre-defined object.
这篇关于REPL和脚本之间的'this'不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!