首页 > Web开发 > 详细

nodejs模块引用

时间:2017-10-01 16:47:37      阅读:327      评论:0      收藏:0      [点我收藏+]

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

nodejs模块引用

原文:http://www.cnblogs.com/puffmoff/p/7617368.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!