LoginSignup
11
4

More than 3 years have passed since last update.

【Node.js】定義したクラスを別のファイルで使用する

Posted at

定義したクラスを別のファイルで使用するには、module.exportsを使います。

まず元となるクラスを作成

smartPhone.js
class iphone {
    constructor() {
    }

    call(){
        console.log('call');
    }

    mail(){
        console.log('mail');
    }

}


class android {
    constructor() {
    }

    call(){
        console.log('call');
    }

    mail(){
        console.log('mail');
    }

}

module.exportsで外部に公開します。

smartPhone.js
module.exports = iphone

これだけで、外部へ公開することができます。
しかし、今回クラスは2つあります。
クラスが複数ある場合はどうするかというと、objectにしてしまいます。

smartPhone.js
module.exports = {
    IPHONE: iphone,
    ANDROID: android
}

Keyは適当な名前、valueはクラス名を設定します。
これで指定したクラスが外部から読み込めるようになりました。

早速別ファイルから読み込んでみます。
requireで呼び出します。

usePhone.js
const iphone = require('./smartphone').IPHONE
const android = require('./smartphone').ANDROID

requireの引数にファイル名を指定します。".js"は省略可能です。
上記ではクラスごとで定数に代入していますが、わざわざこんなことはしません。

usePhone.js
const {IPHONE,ANDROID} = require('./smartphone')

分割代入をします。

あとはクラスをnewすればOKです。

usePhone
const a = new IPHONE()
a.call()

const b = new ANDROID()
b.call()
11
4
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
11
4