LoginSignup
0
0

More than 1 year has passed since last update.

【javascript】prototypeの継承

Last updated at Posted at 2021-11-18

prototypeの継承

以下のような、prototypeを持つコンストラクタがあったとする。


function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

新たに、japaneseというコンストラクタを用意したい。

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

function Japanese(name, age){
  this.name = name;
  this.age = age;
}

Japanese.prototype.hello = function() {
  console.log('hello ' + this.name);
}

同じ内容を記述しているので、冗長であり、メンテナンス性が悪い。

継承

Perosnのprototypeを継承すれば楽。

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

function Japanese(name, age){
  this.name = name;
  this.age = age;
}

// からのオブジェクトを用意し、Person.prototypeを作成している。
Japanese.prototype = Object.create(Person.prototype)

継承ができている。

スクリーンショット 2021-11-18 16.33.05.png

callメソッドを使用してコンストラクタ内部も継承する。

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

function Japanese(name, age){
  Person.call(this. name, age)
}
//call(第一引数:japaneseコンストラクタのthisをPersonに渡している。
// 第二引数:japaneseコンストラクタのnameをPersonに渡している。
//第三引数:japaneseコンストラクタのageをPersonに渡している。

Japanese.prototype = Object.create(Person.prototype)

const takashi = new Japanese('takashi', 23)
console.log(takashi) >> Japanese {name: 'takashi', age: 23}
takashi.hello() >> hello takashi

prototypeの上書き

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

//Japaneseコンストラクタにgenderを拡張することができる。
function Japanese(name, age, gender){
  Person.call(this, name, age)
  this.gender = gender;
}

Japanese.prototype = Object.create(Person.prototype)

//Japanse.protorypeは独立して作成できるので、byeメソッドを拡張している。
Japanese.prototype.bye = function() {
  console.log('こんにちは ' + this.name);
}

const takashi = new Japanese('takashi', 23, '男性')
console.log(takashi)
takashi.hello()
takashi.bye()
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