nodejs中引用其餘js文件中的函數

基本語句

require('js文件路徑');

使用方法

舉個例子,在同一個目錄下,有appfun1fun2三個js文件。app

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();

能夠看到fun1fun2的寫法略有不一樣,fun1這種寫法更好,由於它能夠只把別的文件須要調用的函數導出,未導出的函數別的js文件是用不了的函數

輸出結果以下

調用了app的test方法
調用了fun1的add方法
3
調用了fun2的print方法
相關文章
相關標籤/搜索