admin管理员组文章数量:1323723
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?
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?
Share Improve this question asked Dec 31, 2013 at 17:29 Maciej GoszczyckiMaciej Goszczycki 1,12812 silver badges26 bronze badges 02 Answers
Reset to default 13Node'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.
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.
本文标签: javascript39this39 different between REPL and scriptStack Overflow
版权声明:本文标题:javascript - 'this' different between REPL and script - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742121144a2421704.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论