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方法