LoginSignup
1
1

More than 1 year has passed since last update.

【JavaScript】関数とオブジェクト⑰ super

Posted at

はじめに

Udemyの【JS】ガチで学びたい人のためのJavaScriptメカニズムの講座の振り返りです。

前回の記事

目的

  • 関数とオブジェクトについての理解を深める

本題

1.super

superとは継承元の関数を呼び出すキーワード

例1

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の前に新たにthisを使ってプロパティを設定すると絵エラーになる
        // 必ず先に初期化
        super(name, age);
        this.gender = gender;
    }

    hello() {
        // superは継承元のコンストラクターだけでなくメソッドも呼び出せる
        super.hello();
        console.log('Konnichiwa ' + this.name);
    }

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

const taro = new Japanese('Taro', 23, 'Male');
console.log(taro);
// 下記のhelloメソッドを使うとsuper.hello();はPersonのhelloメソッドを使っているので
// hello Taroと出力される
taro.hello();

例2

使用する上で注意すること
オブジェクトの中で呼べる

前提

// americanという関数を定義
const american = {
    hello() {
        console.log('hello ' + this.name);
    }
}

// bobという関数を定義
const bob = {
    name: 'Bob',
    hello() {
        console.log('hello ' + this.name)
    }
}
// 出力結果:hello Bob
bob.hello();

ここでbobというオブジェクトに対してamericanオブジェクトをプロトタイプに追加します

基本構文.
Object.setPrototypeof(A,B)

A = オブジェクト
B = Aに継承させたいオブジェクト

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

const bob = {
    name: 'Bob',
    // hello() {
    //     console.log('hello ' + this.name)
    // }
}
// ,下記のようにするとコンソールでbobの中にhelloが継承されていることが確認できる
// よってbobのhellメソッドを消してもhello Bobと出力される(プロトタイプをさかのぼってamericanに行き着いた)
Object.setPrototypeOf(bob, american);
bob.hello();

superはクラスの中で使用されるもの

今日はここまで!

参考にさせて頂いた記事

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