码迷,mamicode.com
首页 > Web开发 > 详细

node.js 的 exports 和 module.exports 的区别

时间:2015-08-28 00:22:47      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

commonjs

node.js 的模块系统就是按照模块化规范 commonjs 来实现的:

var math = require("math");

math.add(1, 2);

 

exports 和 module.exports

node.js 实现模块化最常用的函数就是 exports 和 module.exports。

exports 是指向 module.exports 的引用。它们初始化都是为{},require() 返回的是 module.exports,所以当改变了 module.exports 的值时,exports 的值就失效了[2]

 

用法一

// rocker.js

exports.hello = function() {
  console.log("hello world!");
};

// main.js

var r = require("./rocker.js");
r.hello();

 

用法二

// info.js

module.exports = function(name, age) {
  this.name = name;
  this.age = age;
  this.info = function() {
    console.log("姓名:" + name + ", 年龄:" + age + ".");
  };
};

// main.js

var i = require("./info.js");
var info = new i("imzhi", "26");
info.info();

//输出:姓名:imzhi, 年龄:26.

 

用法三

为了避免module.exports重定义之后影响exports的使用,一般会写成:

var useful_module = exports = module.exports = some....

这样再用 exports 赋值属性也没有问题了!

 

总结

一句话总结它们之间的区别[1]If you want the root of your module’s export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports.

 

参考资料:

[1] 一句话说清exports和module.exports的区别

[2] exports 和 module.exports 的区别

[3] Node.js中exports与module.exports的区别

[4] exports vs module.exports

 

node.js 的 exports 和 module.exports 的区别

标签:

原文地址:http://www.cnblogs.com/yxzblue/p/4763690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!