目次
概要:
各オブジェクトには、別のオブジェクトへの内部リンクがあるのはプロトタイプと言います。JavaScriptオブジェクトはプロトタイプからプロパティとメソッドを引き継ぎます。
ArrayオブジェクトはArray.prototypeから引き継ぎます。
MapオブジェクトはMap.prototypeから引き継ぎます。
ShirtオブジェクトはShirt.prototypeから引き継ぎます。
DateオブジェクトはDate.prototypeから引き継ぎます。
Object.prototypeは引き継ぎ順番の一番上にあります。
Array.prototype、Map.prototype、Shirt.prototype、Date.prototypeはObject.prototypeから引き継ぎます。
プロトタイプ継承使って既存のオブジェクトに新しいプロパティとメソッドの追加できます。
オブジェクトコンストラクタにも新しいプロパティとメソッドの追加ができます。
オブジェクトコンストラクタにも新しいプロパティの追加:
function Shirt(color, size) {
this.color = color;
this.size = size;
}
Shirt.prototype.brand = "ザラ";
const cloth = new Shirt("青", 35);
console.log("私のシャツのブランドは" + cloth.brand + "です。")
アウトプット:
私のシャツのブランドはザラです。
オブジェクトコンストラクタにも新しいメソッドの追加:
function Shirt(color, size) {
this.color = color;
this.size = size;
}
Shirt.prototype.colorSize = function() {
return "サイズは"+ this.size + ",色は" + this.color + "。"
};
const cloth = new Shirt("青", 35);
console.log("私の服" + cloth.colorSize())
アウトプット:
私の服サイズは35,色は青。