简体   繁体   English

为什么节点中的 console.log(this) 返回一个空对象?

[英]Why does console.log(this) in node return an empty object?

When I ran console.log(this) in node it returns empty object当我在节点中运行 console.log(this) 时,它返回空对象

console.log(this)             // return { }

But when I used IIFE in node但是当我在节点中使用 IIFE

(function printThisObject(){
   console.log(this);         // return the global object
})();

Can someone explain this to me ?谁可以给我解释一下这个 ?

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).因为 NodeJS 在module 中运行您的代码,并且this引用了它为您的模块导出创建的对象(这也是它为您提供的module变量上的exports属性)。 (As they don't really mention that in the module documentation , I suspect using it is probably not a great idea — use exports instead.) (因为他们并没有在模块文档中真正提到这一点,我怀疑使用它可能不是一个好主意 - 改用exports 。)

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.但是您调用 IIFE 的代码使用this引用全局对象来调用它,因为在松散(非严格)模式下,不通过对象属性调用普通函数将this设置为全局对象。 (In strict mode, this would be undefined there.) (在严格模式下, this在那里是undefined 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM