最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does console.log(this) in node return an empty object? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 13

Because 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.)

发布评论

评论列表(0)

  1. 暂无评论