LoginSignup
0
0

【JavaScript】プロトタイプ継承

Last updated at Posted at 2023-05-24

プロトタイプ継承

別のコンストラクター関数のプロトタイプを継承して機能を流用できるようにすること

※「継承」とは違う
継承は別のコンストラクター関数自体を受け継ぐこと

.js
// 親クラス
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// 親クラスのプロトタイプにhelloメソッドを定義
Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

// 子クラス
function Japanese(name, age, gender) {
  // 親クラスのコンストラクタを呼び出して、親クラスのプロパティを継承
  Person.call(this, name, age);
  
  // 子クラス固有のプロパティを定義
  this.gender = gender;
}

// 子クラスのプロトタイプを親クラスのプロトタイプを継承して作成
Japanese.prototype = Object.create(Person.prototype);

// 子クラスのプロトタイプに子クラス固有のメソッドを定義
Japanese.prototype.Yey = function() {
  console.log('いえーい ' + this.name);
}

// 子クラスのプロトタイプに親クラスのメソッドを上書きすることも可能
// Japanese.prototype.hello = function() {
//   console.log('こんにちは ' + this.name);
// }

// 子クラスのインスタンスを生成
const taro = new Japanese('Taro', 33);

console.log(taro); // Japaneseオブジェクトにnameとageが、prototypeにはPersonが含まれている

taro.hello(); // hello Taroが出力される
taro.Yey(); // いえーい Taroが出力される
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