node.js 学习笔记之 module.exports与exports

在nodejs模块中,若是但愿向外暴露出模块中的方法和变量,须要使用module.exports或者exports,可是他们的意义却不一样。javascript

  • module.exports

module表示该模块对象,在module对象中有个exports的属性,默认值为空对象{};exports是模块往外暴露方法或者变量的接口,能够暴露变量或者方法:java

javascriptvar a =  10;
module.exports = a;
javascriptvar a =  10;
var b = 'hello';
module.exports = {age:a,name:b};
javascriptvar a =  {
    name : 'hello',
    age: 10
}
module.exports = a;
javascriptfunction a(){
    console.log('hello')
}
module.exports = a;
javascriptvar a = function (){
    console.log('hello')
}
module.exports = a;
javascriptvar a = {
    name : 'hello',
    getName : function(){
        console.log(this.name)
    }
}
module.exports = a;
  • exports

exports是module.exports的一个引用,能够为exports添加属性,但不能直接赋值,那样就会失去对module.exports的引用,便不会暴露出所的值。node

javascriptexports.name = 'hello';
javascriptexports.getName = function(){
    console.log(this.name)
}

由于是module.exports的引用,因此每次为exports赋值的时候,就是为module.exports赋值。
若是直接为exports赋值:this

javascriptexports = 'hello';

即改变了exports对module.exports的引用,因此所赋的值没法经过module.exports暴露出去。code

  • exports = module.exports = xxx

能够在不少项目中看到这句,当模块要输出一个非Object时(好比一个Function),可使用对象

javascriptmodule.exports = function () {}

此时 module.exports 被覆盖了,而 exports 仍是原来的对像的引用,为了不在后面的代码中仍然使用 exports.xx = yy 而致使不能正确输出,须要把 exports 变量也从新设置为新的 module.exports 的引用,因此通常习惯写成接口

javascriptexports = module.exports = xxx
相关文章
相关标签/搜索