JS“THIS”内容输出在 CommonJS 模块中获得不同的结果 [重复]

JS "THIS" content output getting a different result in CommonJS module [duplicate]

提问人:Derek Yi 提问时间:12/9/2021 最后编辑:Derek Yi 更新时间:12/9/2021 访问量:154

问:

当我在下面的代码中测试“this”在不同阶段所指的内容时,我预计最后一个输出是 global 的内容,但它显示的是 {}。

var hero = {
  name: 'Monkey',
  sayMyName: function() {
    console.log(this.name);
  }
};

hero.sayMyName();   // A'Monkey'

var speakOut = hero.sayMyName;
speakOut();         // B global

const someone = { name: 'passenger' }

hero.sayMyName.call(someone);  // C'passenger'

function here() {
  console.log(this);
}

 const there = () => {
   console.log(this);
 }

here();   // D global
there();  // E global

输出

monkey
undefined
passenger
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  }
}
{}

有谁知道为什么?

javascript node.js 这个

评论

1赞 T.J. Crowder 12/9/2021
从输出中可以清楚地看出,您正在松散模式下的 Node.js CommonJS 模块(不是 ESM 模块,也不是全局范围)运行此代码。B 是因为,正如您所说,在调用期间引用了没有属性的全局对象。D 是全局对象,因为你在松散模式下调用函数而不设置为任何特定内容,因此它被设置为全局对象。E 是模块的对象,因为这是 CommonJS Node.js 模块的顶级范围中的内容,箭头函数关闭。undefinedthisnamethismodule.exportsthisthis
1赞 T.J. Crowder 12/9/2021
这个问题实际上归结为:“在CommonJS Node.js模块的顶级范围内有什么价值?答案是:模块的对象(最初是空的)。如果你通过(并且你没有with,这将使模块ESM而不是CommonJS)放入并运行它,你会看到.thismodule.exportsconsole.log(this === module.exports);example.jsnode example.jspackage.json"type": "module"true
1赞 Derek Yi 12/9/2021
@T.J.Crowder非常感谢TJ!很高兴了解有关 module.exports 的更多信息。

答: 暂无答案