require('js文件路径');
举个例子,在同一个目录下,有app
、fun1
、fun2
三个js文件。app
var fun1 = require('./fun1'); var fun2 = require('./fun2'); function test(){ console.log("调用了app的test方法"); fun1.add(1,2); fun2(); } test();
function reduce(a,b){ console.log("调用了fun1的reduce方法"); console.log(a-b); } function add(a,b){ console.log("调用了fun1的add方法"); console.log(a+b); } module.exports = { reduce, add }
module.exports = function print(){ console.log("调用了fun2的print方法"); } 这种的调用方法为: fun2(); 或者 module.exports = { print:function(){ console.log("调用了fun2的print方法"); }, copy:function(a,b){ console.log("我是fun2的copy方法"); } } 这种的调用方法为:fun2.print();
能够看到fun1
和fun2
的写法略有不一样,fun1
这种写法更好,由于它能够只把别的文件须要调用的函数导出,未导出的函数别的js文件是用不了的函数
调用了app的test方法 调用了fun1的add方法 3 调用了fun2的print方法