nodejs模块引用

模块的引用是后端语言非常重要的一部分,那么在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只返回一个对象。

转载于:https://www.cnblogs.com/puffmoff/p/7617368.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值