当通过节点js使用CommonJS模块化时,Javascript构造函数何时执行?
在模块到节点的CommonJS实现中,我有以下infantModule.js: 文件名:infantModule.js当通过节点js使用CommonJS模块化时,Javascript构造函数何时执行?,javascript,node.js,commonjs,Javascript,Node.js,Commonjs,在模块到节点的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 = infantIn
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,例如:
infantInstance.gender = 'male';
文件名: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)
由于my infantModule公开了一个现成的实例化对象,因此,除index.js入口点之外的任何其他模块对该模块的所有其他未来需求都将引用此相同的对象,其行为类似于应用程序中的共享实例,这样说是否正确
如果index.js底部还有一行代码,例如:
infantInstance.gender = 'male';
我的应用程序中除index.js之外的任何其他模块,如果在将来某个时间点需要使用infantModule,则将获得更改了性别属性的对象,这是正确的假设吗?
require
返回正常对象。当你接触到那个物体时,没有什么神奇的事情发生
具体来说,第一次调用require()
,节点将执行所需文件的全部内容,然后返回其模块.exports
属性的值