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

本文标签: javascriptWhy does consolelog(this) in node return an empty objectStack Overflow