LoginSignup
0
0

More than 1 year has passed since last update.

Javascript_クラスを作る

Posted at

はじめに

Javascriptでクラスの作り方を学んだのでメモ。
継承の考え方がしっくりこなかったので殴り書き

内容

Messageクラスを作る
class Message {
    //↓コンストラクタに情報を設定する。
    constructor(title, text) {
      this.title = title;
      this.text = text;
    }
    //↓メソッドでアクションを設定する
    success() {
      console.log("正常に投稿されました。");
    }
    
    info() {
      this.success();
      console.log(`タイトルは${this.title}です。`);
      console.log(`内容は「${this.text}」です。`);
    }
  }
  
  const testmessage = new Message("test", "配信テスト。本文はここに表示されます。");
  testmessage.info();

実行結果:
タイトルはtestです。
内容は「本文はここに表示されます。」です。

Messageクラスを継承してAlertMessageクラスを作る
class Message {
    constructor(title, text) {
      this.title = title;
      this.text = text;
    }
    
    success() {
      console.log("正常に投稿されました。");
    }
    
    info() {
      this.success();
      console.log(`タイトルは${this.title}です。`);
      console.log(`内容は「${this.text}」です。`);
    }
}

class AlertMessage extends Message {
    alert(){
      console.log("注意:これは開発者向けのメッセージです。");
    }
    
    info(){
      this.alert();
      console.log(`タイトルは${this.title}です。`);
      console.log(`内容は「${this.text}」です。`);     
    }
}

const message = new AlertMessage("test", "本文はここに表示されます。");
message.info();

実行結果:
注意:これは開発者向けのメッセージです。
タイトルはtestです。
内容は「本文はここに表示されます。」です。

0
0
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
0
0