提问人:Derek Yi 提问时间:12/9/2021 最后编辑:Derek Yi 更新时间:12/9/2021 访问量:154
JS“THIS”内容输出在 CommonJS 模块中获得不同的结果 [重复]
JS "THIS" content output getting a different result in CommonJS module [duplicate]
问:
当我在下面的代码中测试“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]
}
}
{}
有谁知道为什么?
答: 暂无答案
评论
undefined
this
name
this
module.exports
this
this
this
module.exports
console.log(this === module.exports);
example.js
node example.js
package.json
"type": "module"
true