分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

nodejs模块引用

发布时间:2023-09-06 01:15责任编辑:胡小海关键词:jsnodejs

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved