LoginSignup
0
0

More than 1 year has passed since last update.

クラス

Javascriptにおいては、
コンストラクター関数をクラスっぽく表記したもの
*他言語ではコンストラクターよりもクラスの方が使われる

記述方法

class Product{

    constructor(name,price){
       
        this.name = name;
        this.price = price;
    }
//各インスタンスが参照するメソッドを定義
    display(){
        console.log(`名前:${this.name} 値段:${this.price}円`);
    }
    
}

書き方

1.クラスを記述

class Product{
// 
  }
}

2. constructorの記述:クラスを生成した瞬間呼ばれるもの

→name,ageなどのプロパティを作成するときはこちらに入れましょう。

class Product{
 // thisの設定、プロパティの初期化
    constructor(name,price){
       
        this.name = name;
        this.price = price;
    }
    
}

3.メソッドの設定

class Product{

    constructor(name,price){
       
        this.name = name;
        this.price = price;
    }
//各インスタンスが参照するメソッドを定義
    display(){
        console.log(`名前:${this.name} 値段:${this.price}円`);
    }
    
}

4.インスタンスの生成

const beef = new Product("Beef",300);

const beef = new Product("Pork",200);

5.呼び出す

beef.name
beef.display()

→デバックするとこんな感じになります。
スクリーンショット 2022-09-05 22.52.33.png

継承

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

    hello() {
        console.log('hello ' + this.name);
    }
}

class Japanese extends Person {
    constructor(name, age, gender) {
        super(name, age);
        this.gender = gender;
    }

    hello() {
        console.log('Konnichiwa ' + this.name);
    }

    bye() {
        console.log('Sayonara ' + this.name);
    }
}

const taro = new Japanese('Taro', 23, 'Male');
console.log(taro);
taro.bye()

クラス特有の継承のための記述

1.継承先のクラスを『extends 継承元』を加えて記述

class Japanese extends Person {

    }

2.constructorを『super(元の引数);』を加えて記述

class Japanese extends Person {
    constructor(name, age, gender) {
        super(name, age);

    }

3.追加する処理を加える

class Japanese extends Person {
    constructor(name, age, gender) {
        super(name, age);
        this.gender = gender;
    }

4.呼び出す

const taro = new Japanese('Taro', 23, 'Male');
console.log(taro);
taro.bye()

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