module.exports和exports都是用于公开模块接口.不同的是:
1.exports公开的接口对象是module.exports接口对象的引用
2.使用require引入的模块对象是module.exports对象.
如果使用module.exports公开模块接口,require导入的对象就是模块本身
如果使用exports公开模块接口,require导入的对象就是模块对象,这时使用模块的属性或者方法: .属性名或者.方法
例如:
使用exports公开模块接口:
module2.js如下:
//把sama方法对外公开 function sama() { console.info("this sama have money:$1000000000"); } //把sama方法作为s公开,调用时应使用s,s代表sama方法 exports.s = sama; //module.exports = sama;
test.js如下:
//引入模块 var module2 = require("./module2"); //输出模块对象 console.info(module2); /** * 上面输出结果: * { s: [Function: sama] } * 很明显它是一个对象,它有一个属性s,是一个方法.所以这样调用:module2.s(); */ module2.s(); //module2();
使用module.exports公开模块接口:
module2.js
//把sama方法对外公开 function sama() { console.info("this sama have money:$1000000000"); } module.exports = sama;
test.js
//引入模块 var module2 = require("./module2"); //调用模块的方法 console.info(module2); /** * 输出如下: * [Function: sama] * 很明显引入的模块对象就是模块本身,是一个方法.所以这样调用即可:module2(); */ module2();