LoginSignup
0
0

More than 1 year has passed since last update.

【javascript】コンストラクタ関数で継承→メソッドは継承されない。classで継承→メソッドも継承される。

Posted at

はじめに

初学者です。MDN Web DocsでJavaScriptを勉強しています。
継承におけるコンストラクタ関数とクラスの違いを学びとして記載します。

内容

コンストラクタ関数を使用して継承した場合、子に親コンストラクタ関数のメソッドは継承されません。

コンストラクタ関数の場合
// 親コンストラクタ関数
function Parent(age) {
  this.age = age;
};
// prototypeを使ってtestメソッドを追加
Parent.prototype.test = function() {
  console.log(`これはtest用メソッドです。`); 
};

// 子コンストラクタ関数
function Child(age) {
  Parent.call(age);
};
コンソール
Child.prototype.test
=> undefined
// testメソッドは定義されていないと表示される

以下のような方法でメソッドを継承させる必要があるようです。
Teacher()のプロトタイプ とコンストラクタの参照への設定方法

しかし、以下のようにクラスを使用して継承した場合、子クラスは親のメソッドも継承します。

test.rb

// 親クラス
class Parent {
  constructor(age) {
    this.age = age;
  }

  test() {
    console.log(`これはtest用メソッドです。`);
  }
};

// 子クラス
class Child extends Parent {
  constructor(age) {
    super(age);
  }
}
コンソール
Child.prototype.test
=> function test()
// 子クラスにtestメソッドが継承されている

学び

上記の様な点からコンストラクタ関数よりもクラスを使っていったほうが望ましいな、と思いました。

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