LoginSignup
5
3

More than 5 years have passed since last update.

node モジュールの書き方メモ

Last updated at Posted at 2017-01-04

プログラムが大きくなってしまったので、ファイルを分割し、一部の関数を移動する。


var modtest = require('./module_test.js');

といったプログラムで、関数ファイルを読み込みを行いたい。

  • 読み込まれる関数

module.exportsをファイルの先頭に置く。

module_test.js
module.exports = {
  create: TestFunction,        //読み込まれる関数名
}

function TestFunction(){  return{   //関数の実体

    mMatrix:[],         //メンバー変数(配列)
    mResult:undefined,  //メンバー変数

    fAdd1 : function( a, b ){
        this.mResult = a + b;
    },

    fAdd2 : function( a, b ){
        this.mMatrix[0]=a;
        this.mMatrix[1]=b;
        return( a + b );
    },

    ffunc : function( a, b, callback ){ //関数を受け渡す
        this.mResult =callback( a,b );
        return(this.mResult);
    },
}};
  • 読み込む側の関数
test.js
var modtest = require('./module_test.js');  //関数読み込み
// a1 が TestFunction としてクリエイトされる。
var a1 = modtest.create();  //関数のクリエイト

//TestFunction.fAdd1 をcall する
a1.fAdd1( 10, 20 );
console.log( a1.mResult );  //結果表示、a1のメンバー変数mResultを表示する。

//TestFunction.fAdd2 をcall する
console.log( a1.fAdd2( 30, 40 ) );
console.log( a1.mMatrix[0] );   //a1のメンバー変数mMatrix[0]を表示する。
console.log( a1.mMatrix[1] );   //a1のメンバー変数mMatrix[1]を表示する。

//TestFunction に関数を受け渡す
console.log( a1.ffunc( 10, 50, function(a,b){ return b-a; } ));

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3