When是通过node js使用CommonJS模块化时执行的Javascript构造函数

When is a Javascript constructor function executed when using CommonJS modularity through node js?

本文关键字:模块化 执行 构造函数 Javascript CommonJS 使用 node js When      更新时间:2023-09-26

在通过Node实现模块的CommonJS中,我有这个infantModule.js:

文件名:infantModule.js

var infant = function(gender) {
    this.gender = gender;
    //technically, when passed though this line, I'm born!
};
var infantInstance = new infant('female');
module.exports = infantInstance;

我的问题是:

考虑到其他模块消耗这个infantModule,这个模块的构造函数什么时候真正执行,例如:

filename:index.js--应用程序的入口点

var infantPerson = require('./infantModule');
// is it "born" at this line? (1st time it is "required")
console.log(infantPerson);
// or is it "born" at this line? (1st time it is referenced)

由于我的infantModule公开了一个现成的实例化对象,因此该模块的所有其他未来需求,除了index.js入口点之外的任何其他模块,都将引用这个相同的对象,它的行为就像应用程序中的共享实例,这样说正确吗?

如果在index.js的底部有一行额外的代码,例如:

infantInstance.gender = 'male';

除了index.js之外,我的应用程序中的任何其他模块,在未来的某个时间点都需要infantModule,都会更改具有性别属性的对象,这是正确的假设吗?

require返回一个普通对象。当您访问该对象时,不会发生任何神奇的事情。

具体来说,第一次调用require()时,Node将执行所需文件的全部内容,然后返回其module.exports属性的值。