module.exports objects are created by the module system. When we write a module ourselves, we need to write the module interface at the end of the module to declare that the module exposes the declaration content to the outside world. module.exports provides a method for exposing the interface.
1. Return a JSON object
1 var app = { 2 name:'app', 3 version:'1.0.0', 4 sayName:function(name) { 5 console.log(this.name); 6 } 7 } 8 9 module.exports = app;
This method can return a globally shared variable or method.
Call method:
1 var app = require("./app.js"); 2 app.sayName('hello');//hello
Or use it like this:
1 var func1 = function(){ 2 console.log("func1"); 3 }; 4 5 var func2 = function(){ 6 console.log("fun2"); 7 }; 8 9 exports.function1 = func1; 10 exports.function2 = func2;
The calling method is:
var functions = require("./functions"); functions.function1(); functions.function2();
2. Return a constructor
CLASS.js
var CLASS = function(args) { this.args = args; } module.exports = CLASS;
transfer:
var CLASS = require("./CLASS.js"); var c = new CLASS('arguments');
3. Return an instance object:
//CLASS.js var CLASS = function() { this.name = "class"; } CLASS.prototype.func = function(){ alert(this.name); } module.exports = new CLASS();
transfer:
var c = require("./CLASS.js"); c.func();//"class"