`
rainsilence
  • 浏览: 158768 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

NodeJS module.exports VS exports

 
阅读更多

 

node.js通过实现CommonJS的Modules/1.0标准引入了模块(module)概念,一个模块可以通过module.exports或exports将函数、变量等导出,以使其它JavaScript脚本通过require()函数引入并使用。

现在有一个问题:到底应该用module.exports还是用exports呢?

console.log(module.exports === exports);
 

 代码比较,其实两者是一样的

node在执行的时候,实际上是有一个全局变量module,但是,exports却是通过动态生成一个function,作为此function的参数传进来的。

 

那么exports = function() {};之后,只是地址改变。exports的内容并没有改变

那么,如果要实现类似于var assert = require("assert"); assert();这样的代码如何实现?看以下代码:

moduleTest.js

 

var exports = module.exports = function(param) {
	console.log(param);
};

exports.print = function(param) {
	console.log(param + ",we are printing.");
};

 

 

 simple.js

 

var test = require("./moduleTest");

test("I'm John.");

test.print("444");
 

 

So...如果要实现assert的调用,必须

 

exports = module.exports = someObject;

exports.sth = sobj; // 如果还需要加入其他属性则这样写
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics