nodejs 全局变量是否绑定到 "module" 函数?

Does nodejs global variable bind to "module" functions?

据说nodejs在执行js文件时,会在调用全局作用域的函数时绑定this到模块上下文,像这样:

function father(){
    this.id=10
}
father();
console.log(module.id);

它实际上打印的是“.”,而不是我预期的“10”。如果模块是要访问的关键字,我试过这个:

(function (exports, require, module, __filename, __dirname) {
  father();
  console.log(module.id);
})()

但是这次,它在 console.log(module.id) 行抛出一个异常,说

"TypeError: Cannot read property 'id' of undefined.

最后,我尝试了这个:

console.log(this===module);
console.log(this===global);
function f1(){console.log(this===module);}
function f2(){console.log(this===global);}

function g1(){
    return function(){console.log(this===module);};
}
function g2(){
    return function(){console.log(this===global);};
}
f1();
f2();
g1()();
g2()();

它打印出来了:

false
false
false
true
false
true

与建议的第一个答案不同。所以我想知道如何在由 Nodejs 执行的 js 文件中使用 "module" 关键字?

最后一次尝试:

function h(){this.a='abc';}
h()
console.log(module.exports.a);

我希望打印 "abc",但它仍然打印 "undefined"

谢谢。

It's said that nodejs, when executing a js file, will bind "this" to module context

No,绑定到exports。如果你把

console.log(this === module.exports); // or just `exports`

在您的文件中,它将记录 true

when calling function with global scope

没有。模块作用域中的 this 值与函数或它们的调用方式无关。在草率模式下,明明调用的函数中的 this 值将是全局对象,但这与 module 对象不同。

function father() {
    console.log(this === global);
}
father(); // true