LoginSignup
4
2

More than 5 years have passed since last update.

JavaScript の class 構文とプロトタイプチェーン

Last updated at Posted at 2018-09-19

この記事は

JavaScript の class 構文を使った場合に、プロトタイプチェーンがどのようになるかを把握したかったので図にまとめてみた。似たような記事はたくさんあるが、あくまで備忘録として。

コード

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

class Girl extends Person {
  speak() {
    console.log(`わたし、${this.name}。よろしくね!`);
  }
}

const madoka = new Girl('鹿目まどか');
madoka.speak(); // わたし、鹿目まどか。よろしくね!

const kyoko = new Girl('佐倉杏子');
kyoko.speak = function() {
  console.log(`${this.name}だ。よろしくな!`);
};
kyoko.speak(); // 佐倉杏子だ。よろしくな!

スクリーンショット 2018-09-23 20.14.22.png

オブジェクトだけでなく、コンストラクタ関数もチェーンになっているのは知らなかった。そのおかげで static なメソッドも継承できるのか。

Girl.__proto__ === Person; // true
Girl.__proto__.__proto__ === Function.prototype; // true

参考

4
2
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
4
2