基本語句
require('js文件路徑');
使用方法
舉個例子,在同一個目錄下,有app
、fun1
、fun2
三個js文件。
1. app.js
var fun1 = require('./fun1');
var fun2 = require('./fun2');
function test(){
console.log("調用了app的test方法");
fun1.add(1,2);
fun2();
}
test();
2. fun1.js
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
}
3. fun2.js
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方法