0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

superとは

継承するために必要な処理

継承する為にすること2つ

1.継承先 extends 継承元を加える
2.super(継承元の引数を加える);
例)

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.superはconstructorの真下に書くべき

constructor(name, age, gender) {
        super(name, age);
        this.gender = gender;
    }
constructor(name, age, gender) {        
        this.gender = gender;
        super(name, age);
    }
エラーが出てきました。
<a class='gotoLine' href='#54:7'>54:7</a> Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor"

2.継承後に継承『前』のメソッドを呼びたい
1.上記の継承の記述を完了させる
2.継承先のメソッドの中にsuper.継承元のメソッド()を記述
3.メソッドを呼び出す

// 継承元のhelloは'hello '
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

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


// 継承先のhelloは'Konnichiwa  '
class Japanese extends Person {
    constructor(name, age, gender) {
    		super(name, age);
    		this.gender = gender;
        
        
    }

    hello() {
        console.log('Konnichiwa ' + this.name);
// 継承先のhelloの中に継承元のhelloを呼び出したいときは?
        super.hello()
    }

    bye() {
        console.log('Sayonara ' + this.name);
    }
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?