在通过 Node 实现模块的 CommonJS 中,我有这个 BabyModule.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,这个模块的构造函数什么时候真正执行,例如:
文件名: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)
由于我的 BabyModule 公开了一个现成的实例化对象,因此除 index.js 入口点之外的任何其他模块对该模块的所有其他 future 需求都将引用同一个对象,其行为类似于应用程序中的共享实例,这样说对吗?
如果index.js底部多了一行代码,如:
infantInstance.gender = 'male';
除了index.js之外,我的应用程序中的任何其他模块在未来的某个时间点需要infantModule,都会获得性别属性发生变化的对象,这是正确的假设吗?
最佳答案
require
返回一个普通对象。当您访问该对象时,不会发生任何神奇的事情。
具体来说,第一次调用 require()
时,Node 将执行所需文件的全部内容,然后返回其 module.exports
的值属性。
关于javascript - 通过 Node js 使用 CommonJS 模块化时,Javascript 构造函数何时执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34498639/