admin管理员组文章数量:1315303
When I ran console.log(this) in node it returns empty object
console.log(this) // return { }
But when I used IIFE in node
(function printThisObject(){
console.log(this); // return the global object
})();
Can someone explain this to me ?
When I ran console.log(this) in node it returns empty object
console.log(this) // return { }
But when I used IIFE in node
(function printThisObject(){
console.log(this); // return the global object
})();
Can someone explain this to me ?
Share Improve this question edited Aug 12, 2020 at 6:52 DavidHyogo 2,8964 gold badges32 silver badges50 bronze badges asked Mar 6, 2017 at 17:18 Krisan AlifariKrisan Alifari 335 bronze badges 1- 2 Related: How does the “this” keyword work? – Felix Kling Commented Mar 6, 2017 at 17:22
1 Answer
Reset to default 13Because NodeJS runs your code in a module, and this
references the object it creates for your module's exports (which is also the exports
property on the module
variable it provides you). (As they don't really mention that in the module documentation, I suspect using it is probably not a great idea — use exports
instead.)
But your code calling the IIFE calls it with this
referring to the global object, because in loose (non-strict) mode, calling a normal function not through an object property calls it with this
set to the global object. (In strict mode, this
would be undefined
there.)
本文标签: javascriptWhy does consolelog(this) in node return an empty objectStack Overflow
版权声明:本文标题:javascript - Why does console.log(this) in node return an empty object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741977796a2408224.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论