Javascriptのクラス - Javascript

クラス

ES2015(ES6)でクラスが追加されました。

クラスとは、オブジェクトを作成するためのひな形のようなものです。

オブジェクトに設定したいプロパティやメソッドを定義できます。

インスタンスとは?

インスタンスは、「 クラスをもとに生成されたオブジェクト 」を意味しています。

クラスからオブジェクトを生成する処理を「 インスタンス化 」といいます。

インスタンスとオブジェクトは同じ意味のように扱われますが、プログラミング言語や人によって、ニュアンスが違います。

クラスの作成・呼び出し

class Calc {
    constructor(name, price){
        this.name = name;
        this.price = price;
        this.tax = 0.08;
    };

    tax_calc(){
        return this.name + ":" + this.price * this.tax;
    };
};

let orange = new Calc("オレンジ", 100);
console.log(orange.tax_calc());

同じクラス内の関数を呼び出す

class Sample{
  display(){
    this.hello();
  }

  hello(){
    console.log("Hello, World");
  }
}

let sample = new Sample();
sample.display();

クラスの継承

script.js - Node.js

class Goku{
  constructor(){
    this.kamehameha = 10;
    this.kaiouken = false;
    this.magnification = 0;
    this.genkidama = 30
  }

  act_kamehameha(){
    if(this.kaiouken){
      console.log("界王拳かめはめは:" + (this.kamehameha * this.magnification) + "ダメ")
    } else {
      console.log("かめはめは:" + (this.kamehameha) + "ダメ")
    }
  }

  act_genkidama(){
    if(this.kaiouken){
      console.log("界王拳中は使えない。")
    } else {
      console.log("げんき玉:" + this.genkidama + "ダメ");
    }
  }

  set_kaiouken(n){
    this.kaiouken = true;
    this.magnification = n;
    console.log(`界王拳${n}倍`);
  }

  cancell_kaiouken(){
    this.kaiouken = false;
    this.magnification = 0;
    console.log(`界王拳${0}`);
  }

  set_super_saiyazin(){
    console.log("スーパーサイヤ人に変身した。")
    return new SuperSaiyazinGoku();
  }

}

class SuperSaiyazinGoku extends Goku{
  constructor(){
    super();
    this.powerup = 300;
  }

  act_kamehameha(){
    console.log("かめはめは(スーパーサイヤ人):" + (this.kamehameha * this.powerup) + "ダメ")
  }

  set_kaiouken(n){
    console.log("界王拳はつかえない");
  }

  act_genkidama(){
    console.log("げんき玉はつかえない。");
  }
}

let goku = new Goku();
goku.act_kamehameha();
goku.set_kaiouken(10);
goku.act_kamehameha();
goku.cancell_kaiouken();
goku.act_kamehameha();
goku.act_genkidama();

let supersiyazingoku = goku.set_super_saiyazin();
supersiyazingoku.act_kamehameha();
supersiyazingoku.act_genkidama();