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元;

posted @ 2015-12-23 16:27  Jone_chen  阅读(44769)  评论(1编辑  收藏  举报