Node.js的module.export和export方法的区别详解
沉沙 2018-07-26 来源 : 阅读 1109 评论 0

摘要:本篇Node.js教程探讨了Node.js的module.export和export方法的区别,希望阅读本篇文章以后大家有所收获,帮助大家对Node.js的理解更加深入。

你肯定非常熟悉nodejs模块中的exports对象,你可以用它创建你的模块。例如:(假设这是rocker.js文件)

exports.name = function() {

    console.log('My name is Lemmy Kilmister');

};

在另一个文件中你这样引用

var rocker = require('./rocker.js');

rocker.name(); // 'My name is Lemmy Kilmister'

那到底Module.exports是什么呢?它是否合法呢?

其实,Module.exports才是真正的接口,exports只不过是它的一个辅助工具。 最终返回给调用的是Module.exports而不是exports。

所有的exports收集到的属性和方法,都赋值给了Module.exports。当然,这有个前提,就是Module.exports本身不具备任何属性和方法。如果,Module.exports已经具备一些属性和方法,那么exports收集来的信息将被忽略。

修改rocker.js如下:

module.exports = 'ROCK IT!';

exports.name = function() {

    console.log('My name is Lemmy Kilmister');

};

 再次引用执行rocker.js

var rocker = require('./rocker.js');

rocker.name(); // TypeError: Object ROCK IT! has no method 'name'

发现报错:对象“ROCK IT!”没有name方法

rocker模块忽略了exports收集的name方法,返回了一个字符串“ROCK IT!”。由此可知,你的模块并不一定非得返回“实例化对象”。你的模块可以是任何合法的javascript对象--boolean, number, date, JSON, string, function, array等等。

你的模块可以是任何你设置给它的东西。如果你没有显式的给Module.exports设置任何属性和方法,那么你的模块就是exports设置给Module.exports的属性。

下面例子中,你的模块是一个类:

module.exports = function(name, age) {

    this.name = name;

    this.age = age;

    this.about = function() {

        console.log(this.name +' is '+ this.age +' years old');

    };

};

可以这样应用它:

var Rocker = require('./rocker.js');

var r = new Rocker('Ozzy', 62);

r.about(); // Ozzy is 62 years old

下面例子中,你的模块是一个数组:

module.exports = ['Lemmy Kilmister', 'Ozzy Osbourne', 'Ronnie James Dio', 'Steven Tyler', 'Mick Jagger'];

可以这样应用它:

var rocker = require('./rocker.js');

console.log('Rockin in heaven: ' + rocker[2]); //Rockin in heaven: Ronnie James Dio

现在你明白了,如果你想你的模块是一个特定的类型就用Module.exports。如果你想的模块是一个典型的“实例化对象”就用exports。

给Module.exports添加属性类似于给exports添加属性。例如:

module.exports.name = function() {

    console.log('My name is Lemmy Kilmister');

};

同样,exports是这样的

exports.name = function() {

    console.log('My name is Lemmy Kilmister');

};

请注意,这两种结果并不想同。前面已经提到module.exports是真正的接口,exports只不过是它的辅助工具。推荐使用exports导出,除非你打算从原来的“实例化对象”改变成一个类型

API文档是枯燥的,下面本人收集了一些论坛经常有人疑问和开源代码中经常遇到的案例供大家研究一下。

文章博客地址 排版更佳。。

##module.exports与exports的区别

每一个node.js执行文件,都自动创建一个module对象,同时,module对象会创建一个叫exports的属性,初始化的值是 {}

 module.exports = {};

Node.js为了方便地导出功能函数,node.js会自动地实现以下这个语句

foo.js

 exports.a = function(){

 console.log('a')

 }

 exports.a = 1

test.js

 var x = require('./foo');

 console.log(x.a)

看到这里,相信大家都看到答案了,exports是引用 module.exports的值。module.exports 被改变的时候,exports不会被改变,而模块导出的时候,真正导出的执行是module.exports,而不是exports

再看看下面例子

foo.js

 exports.a = function(){

  console.log('a')

 }

 module.exports = {a: 2}

 exports.a = 1

test.js

 var x = require('./foo');

 console.log(x.a)

result:

 2

exports在module.exports 被改变后,失效。

是不是开始有点廓然开朗,下面将会列出开源模块中,经常看到的几个使用方式。

##module.exports = View

function View(name, options) {

   options = options || {};

   this.name = name;

   this.root = options.root;

   var engines = options.engines;

   this.defaultEngine = options.defaultEngine;

   var ext = this.ext = extname(name);

   if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no         extension was provided.');

   if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') +     this.defaultEngine);

   this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);

   this.path = this.lookup(name);

 }

 module.exports = View;

javascript里面有一句话,函数即对象,View 是对象,module.export =View, 即相当于导出整个view对象。外面模块调用它的时候,能够调用View的所有方法。不过需要注意,只有是View的静态方法的时候,才能够被调用,prototype创建的方法,则属于View的私有方法。

foo.js

 function View(){

 }

 View.prototype.test = function(){

  console.log('test')

 }

 View.test1 = function(){

  console.log('test1')

 }

module.exports = View

test.js

 var x = require('./foo');

 console.log(x) //{ [Function: View] test1: [Function] }

 console.log(x.test) //undefined

 console.log(x.test1) //[Function]

 x.test1() //test1

##var app = exports = module.exports = {};

其实,当我们了解到原理后,不难明白这样的写法有点冗余,其实是为了保证,模块的初始化环境是干净的。同时也方便我们,即使改变了 module.exports 指向的对象后,依然能沿用 exports的特性

 exports = module.exports = createApplication;

 /**

  * Expose mime.

  */

 exports.mime = connect.mime;

例子,当中module.exports = createApplication改变了module.exports了,让exports失效,通过exports = module.exports的方法,让其恢复原来的特点。

##exports.init= function(){}

这种最简单,直接就是导出模块 init的方法。

##var mongoose = module.exports = exports = new Mongoose;


本文由职坐标整理发布,更多相关知识,请关注职坐标WEB前端Node.js频道!

本文由 @沉沙 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程