JS オブジェクトのプロトタイプ
1. プロトタイプの継承
すべてのJavaScriptオブジェクトは、プロトタイプ(Prototype)からプロパティおよびメソッドを継承(Inherit)します。
DateオブジェクトはDate.prototypeを継承します。ArrayオブジェクトはArray.prototypeを継承します。
Object.prototype は、プロトタイプ継承チェーンの最上位に位置します。Date オブジェクト、Array オブジェクト、およびその他すべてのオブジェクトは、Object.prototype を継承しています。
2. オブジェクトへのプロパティとメソッドの追加
特定の型の既存のオブジェクトすべてに、新しいプロパティ(またはメソッド)を追加したい場合があります。
あるいは、オブジェクトコンストラクタ(Object Constructor)に新しいプロパティ(またはメソッド)を追加したい場合もあります。
以前のセクションで、オブジェクトコンストラクタの使用方法を学習しました:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");既存のオブジェクトコンストラクタに対して、次のように新しいプロパティを直接追加することはできません:
Person.nationality = "English";コンストラクタに新しいプロパティを追加するには、コンストラクタ関数自体の中に記述する必要があります:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English"; // ここで追加
}3. prototype プロパティの使用
JavaScript の prototype プロパティを使用すると、オブジェクトコンストラクタに対して新しいプロパティを動的に追加できます:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
// コンストラクタのプロトタイプにプロパティを追加
Person.prototype.nationality = "English";また、JavaScript の prototype プロパティを使用して、オブジェクトコンストラクタに新しいメソッドを追加することも可能です:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
// コンストラクタのプロトタイプにメソッドを追加
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};