nodejs模块引用
2024-10-09 15:15:53
模块的引用是后端语言非常重要的一部分,那么在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只返回一个对象。
最新文章
- printf()输出
- Quartz-2D
- 字符串处理 Codeforces Round #296 (Div. 2) B. Error Correct System
- Python学习笔记-Day3-python函数
- BZOJ2243 (树链剖分+线段树)
- 转载:你可能没注意的CSS单位
- 24.allegro中光绘gerber[原创]
- learn-python3
- 用CALayer实现聚光灯效果
- C程序设计语言练习题1-17
- 使用事件CreateEvent注意事项
- 实验排队功能实现(JAVA)
- 10树莓派Samba的安装与配置
- Instruments学习之Allocations
- bzoj5019: [Snoi2017]遗失的答案
- MySQL5.7.20 二进制包无ROOT权限下安装, 滴滴云服务器
- iPhone-获取网络数据或者路径的文件名
- win10 禁用Defender
- docker dockerfile构建自己的tomcat镜像
- golang 自定义类型的排序sort