chiname

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

module.exports和exports的区别

 

JavaScript code?
1
2
3
4
5
6
7
8
9
define(function(require, exports) {
 
  // 对外提供 foo 属性
  exports.foo = 'bar';
 
  // 对外提供 doSomething 方法
  exports.doSomething = function() {};
 
});

 

JavaScript code?

1
2
3
4
5
6
7
8
9
define(function(require, exports, module) {
 
  // 对外提供接口
  module.exports = {
    name: 'a',
    doSomething: function() {};
  };
 
});

首先 exports === module.exports, exports 是 module.exports 的一个引用

通常来说,exports 就够用了
exports.doSomething = function() {};
exports.doOthers = function() {};

但有时,我们想提供整个接口的时候,exports 就不行了
var interface = {doSomething:function(){},doOthers:function(){}}
此时书写起来会非常麻烦,需要这样写:
exports.doSomething = interface.doSomething;
exports.doOthers = interface.doOthers;

所以,这个就可以改变 module.exports 的引用来替换掉整个接口
module.exports = interface;

posted on 2014-03-28 18:57  把我的欢乐带给你  阅读(150)  评论(0)    收藏  举报