模块的引用是后端语言非常重要的一部分,那么在nodejs中,如何做到这一点呢。

在引用其他模块时,常用的就是两种方法:exports,module.exports。

接下来,我们写一个demo来分辨其中的区别

testModule.js:

function User(name,title,post){
this.name=name;
this.title=title;
this.post=post;
}
User.prototype.sayhello = function() {
console.log("hello"+this.name);
};
module.exports=User;

testExports.js:

exports.sayhello=function(name){
console.log('hello,'+name);
}

test.js:

var testmodule=require('./testmodule');
console.log(typeof(testmodule));
var newtestobj=new testmodule('mike','zhejiang','311301');
console.log(typeof(newtestobj));
var testexports=require('./testexports');
console.log(testexports);

运行test.js,依次输出:

function
object
{ sayhello: [Function] }

显而易见的是,module.exports返回的其实是一个构造函数,而exports只返回一个对象。

最新文章

  1. printf()输出
  2. Quartz-2D
  3. 字符串处理 Codeforces Round #296 (Div. 2) B. Error Correct System
  4. Python学习笔记-Day3-python函数
  5. BZOJ2243 (树链剖分+线段树)
  6. 转载:你可能没注意的CSS单位
  7. 24.allegro中光绘gerber[原创]
  8. learn-python3
  9. 用CALayer实现聚光灯效果
  10. C程序设计语言练习题1-17
  11. 使用事件CreateEvent注意事项
  12. 实验排队功能实现(JAVA)
  13. 10树莓派Samba的安装与配置
  14. Instruments学习之Allocations
  15. bzoj5019: [Snoi2017]遗失的答案
  16. MySQL5.7.20 二进制包无ROOT权限下安装, 滴滴云服务器
  17. iPhone-获取网络数据或者路径的文件名
  18. win10 禁用Defender
  19. docker dockerfile构建自己的tomcat镜像
  20. golang 自定义类型的排序sort

热门文章

  1. [转]解析多级json数据为list中嵌套一级字典的形式
  2. 【Java】CAS的乐观锁实现之AtomicInteger源码分析
  3. TLB和MMU的区别
  4. eclipse安装java web插件
  5. KinectFusion解析
  6. Big Event in HDU(多重背包套用模板)
  7. MySQL的ibdata1文件占用过大
  8. python内建函数isinstance基础用法
  9. python3 爬淘女郎
  10. haslib 模块