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 @   Jone_chen  阅读(44844)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示