nodeJs--模块module.exports与实例化方法
在nodejs中,提供了exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。而在exports抛出的接口中,如果你希望你的模块就想为一个特别的对象类型,请使用module.exports;如果希望模块成为一个传统的模块实例,请使用exports.xx方法;module.exports才是真正的接口,exports只不过是它的一个辅助工具。最终返回给调用的是module.exports而不是exports。下面看代码;
首先来看module.exports,新建一个hello.js,代码如下:
module.exports=function(name,age,money){
this.name=name;
this.age=age;
this.money=money;
this.say=function(){
console.log('我的名字叫:'+this.name+',我今年'+this.age+'岁,月薪为:'+this.money+'元;')
}
};
可以看到,module.exports被赋予了一个构造函数;再新建一个main.js,其中引入hello.js这个模块,把exports方法接受进来,main.js代码如下:
var Hello=require('./hello');
var hello=new Hello('jone','28','10000')
hello.say();
进入node环境,运行main.js,可以看到,已经打印出来:我的名字叫:jone,我今年28岁,月薪为:10000元;
而在hello.js中,我们是赋予了exports一个函数 ,当然,也可以采用匿名函数的方式;见代码:
function hello(name,age,money){
this.name=name;
this.age=age;
this.money=money;
this.say=function(){
console.log('我的名字叫:'+this.name+',我今年'+this.age+'岁,月薪为:'+this.money+'元;')
}
}
module.exports=hello;
以上modle.exports,这个模块很明显是一个特别的对象模型;那如果采用对象实例的方法该如何实现呢?其实也很简单,只需要给exports对象负值一个新的方法即可;见下面代码:
function hello(name,age,money){
this.name=name;
this.age=age;
this.money=money;
this.say=function(){
console.log('我的名字叫:'+this.name+',我今年'+this.age+'岁,月薪为:'+this.money+'元;')
}
}
var Hello=new hello('jone','28','10000');
exports.add=Hello
在hello.js中,依然是一个构造函数,声明了一个变量Hello,然后再把Hello赋值给exports自定义的add方法;那么在main.js中,由于add已经是exports的一个自定义的实例方法了,因此我们可以直接这么调用它:Hello.add.say();见代码:
var Hello=require('./hello');
Hello.add.say()
进行node环境,运行main.js,可以看到,结果和上面一样,都会输出:我的名字叫:jone,我今年28岁,月薪为:10000元;
最新文章
- CSS魔法堂:重拾Border之——不仅仅是圆角
- 002:IPC与system函数简介
- ios - 图片自动轮播定时器(NSTimer)以及消息循环模式简介
- Java druid
- Solr 删除数据的几种方式
- HDU - 2276 Kiki &;amp; Little Kiki 2
- BZOJ 1455: 罗马游戏( 配对堆 + 并查集 )
- C# 读取 vCard 格式
- Apache的htaccess文件出现500错误的原因
- hdu_2871_Memory Control(巨恶心线段树)
- [POI2010]CHO-Hamsters
- Linux内核入门到放弃-网络-《深入Linux内核架构》笔记
- webService入门理解
- scrapy 下载图片 from cuiqingcai
- golang语言并发与并行——goroutine和channel的详细理解(一) 转发自https://blog.csdn.net/skh2015java/article/details/60330785
- JVM监控
- PHP开发工具(CodeLobster PHP Edition)
- 为什么TCP连接需要三次握手分开需要四次握手?
- 【BIRT】Format Number下的Round Mode中的各项解释
- [bzoj] 1588 营业额统计 || Splay板子题