javascript - 通过 Node js 使用 CommonJS 模块化时,Javascript 构造函数何时执行?

标签 javascript node.js commonjs

在通过 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/

相关文章:

typescript - 替换 Typescript 包上的 'require'

javascript - jQuery 动画滚动 backgroundColor 不改变

javascript - Express js post方法读取编码数据错误

node.js - 在 NodeJS 中对 SAML2 请求进行数字签名

javascript - 为什么我得到这个 'res.render() is not a function'

node.js - Node net.Socket.on ("data") 事件有保证顺序吗?

javascript - 使用 requireJS 的模块定义的区别

reactjs - 在使用第三方东西时如何保持 Browserify 包大小合理(如果重要的话通过 grunt )

javascript - jQuery/JavaScript 用括号外的逗号分割字符串

javascript - CORS 在 jquery 中工作正常但在 angularjs 中不工作