When是通过node js使用CommonJS模块化时执行的Javascript构造函数
When is a Javascript constructor function executed when using CommonJS modularity through node js?
在通过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
属性的值。
相关文章:
- 聚合物是一个框架而不是一个库.如何模块化地使用web组件
- 使用Ampersand.js路由模块化应用程序
- 性能与模块化:将JS集成到PHP或单独的custom.JS中
- 将broccoliJS与当前使用requireJS的模块化主干应用程序结合使用,我想完全放弃requireJS
- 用于多个选项卡和模块化的knockoutjs设计模式
- 编写在浏览器和node.js中运行的模块化ECMAScript
- 模块化&重用使用ExtJS编写的代码
- 使用模块化CSS与Bootstrap 4和React
- 构建模块化谷歌地图应用程序
- 模块化模块?需要父模块中的部分
- 为什么模块化幂函数在 Python 和 Javascript 中对于大数字的工作方式不同
- 模块化与性能与性能与角度应用程序中的ng-include
- 将变量传递给 Javascript 模块化模式方法
- JavaScript模块化和依赖注入之间的区别
- 无法模块化AngularJS应用程序
- 模块化JS和原型继承
- 如何构建模块化的js承诺链
- jQuery命名空间声明和模块化方法
- 第一个jquery项目-在函数中使用处理程序来模块化它们
- When是通过node js使用CommonJS模块化时执行的Javascript构造函数