LoginSignup
1
2

More than 3 years have passed since last update.

備忘録 javascript におけるクラス

Posted at

どうも未来電子でインターンをしているものです。
今回はjavascriptのクラスについて自分なりにまとめてみました。

私はプログラミング初心者であるため間違っていることがあるかもしれませんが、お手柔らかにお願いします。

目次

・クラス生成
・コンストラクタ
・インスタンスの生成
・メソッド、メソッドの使用
・継承

クラス生成

クラスとは設計図のようなものです

class Human{}

これでHumanというクラスを生成できました。

コンストラクタ

コンストラクタにはクラスから生成されたオブジェクトの初期化という機能があります。

class Human{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

メソッド、メソッドの使用

メソッドでは具体的な処理について書きます。
コンストラクタで定めた変数を使えます。

class Human{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    profile(){
        console.log(`私の名前は${this.name}${this.age}歳です`);
    }
}

ここではprofileというメソッドを追加しました。
このメソッドを使用するには

consot bokuno_profile = new Human("boku", 20);
console.log(bokuno_profile.profile);

>>>`私の名前はboku、20歳です`

以上のように新たにインスタンスを生成する場合はnewを使い変数を代入して定義します。
メソッドを使う場合はインスタンス名の後にメソッド名を書きます。

1
2
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
1
2