
Java Scriptの基礎その27 クラスとプロトタイプ その2
イントロダクション
JavaScriptでのオブジェクト指向プログラミングは、クラスとプロトタイプという2つの主要な方法で実現されます。本記事では、JavaScriptでのクラスとプロトタイプを使ったオブジェクト指向プログラミングの基本的な概念を、具体的なコード例と共に解説します。特に、「use strict」モードのコードを使い、3つの方法でオブジェクトを定義し、継承とメソッドの使用方法を見ていきます。
コンストラクタ関数とプロトタイプ
personDataコンストラクタ関数
最初に、コンストラクタ関数を使用したオブジェクトの定義方法を説明します。以下のコードは、personDataというコンストラクタ関数を定義しています。
const currentYear = 2024;
const personData = function (firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
};
personData.prototype.calcAge = function () {
console.log(currentYear - this.birthYear); // 年齢を計算し、出力します
};
personData関数はfirstNameとbirthYearという2つのプロパティを持つオブジェクトを作成します。
calcAgeメソッドはbirthYearを使って年齢を計算し、コンソールに出力します。
studentDataコンストラクタ関数
次に、personDataを継承するstudentDataコンストラクタ関数を定義します。
const studentData = function (firstName, birthYear, courseTitle) {
personData.call(this, firstName, birthYear);
this.courseTitle = courseTitle;
};
studentData.prototype = Object.create(personData.prototype);
studentData.prototype.introduce = function () {
console.log(`My name is ${this.firstName} and I study ${this.courseTitle}`); // 自己紹介を出力します
};
studentDataはpersonDataを継承し、courseTitleという新しいプロパティを追加します。
introduceメソッドは、firstNameとcourseTitleを使って自己紹介を出力します。
インスタンスの作成とメソッドの呼び出し
const bruceWayne = new studentData("Bruce", 2002, "Computer Science");
bruceWayne.introduce(); // My name is Bruce and I study Computer Science
const mikeMyers = new studentData("Mike", 1963, "Acting");
mikeMyers.calcAge(); // 61
console.log(mikeMyers.__proto__); // studentDataのプロトタイプ
console.log(mikeMyers.__proto__.__proto__); // personDataのプロトタイプ
console.log(mikeMyers instanceof studentData); // true
console.log(mikeMyers instanceof personData); // true
console.log(mikeMyers instanceof Object); // true
bruceWayneとmikeMyersという2つのインスタンスを作成し、それぞれのメソッドを呼び出して結果を確認します。
クラス構文を使った定義
personClassクラス
次に、ES6以降のクラス構文を使って同じ機能を実装します。
class personClass {
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
calculateAge() {
console.log(currentYear - this.birthYear); // 年齢を計算し、出力します
}
greetingHello() {
console.log(`Hello, my name is ${this.fullName}`); // 挨拶を出力します
}
oneLiner() {
console.log(
`${this.fullName} is ${currentYear - this.birthYear} years old`
); // 一行で情報を出力します
}
}
personClassはコンストラクタメソッドでfullNameとbirthYearを初期化します。
calculateAge, greetingHello, oneLinerの3つのメソッドを持ちます。
studentClassクラス
personClassを継承するstudentClassを定義します。
class studentClass extends personClass {
constructor(fullName, birthYear, courseTitle) {
super(fullName, birthYear);
this.courseTitle = courseTitle;
}
introduceSelf() {
console.log(`My name is ${this.fullName} and I study ${this.courseTitle}`); // 自己紹介を出力します
}
oneLiner() {
console.log(
`${this.fullName} will be ${
currentYear - this.birthYear + 1
} years old next year.`
); // 一行で情報を出力します
}
}
studentClassはpersonClassを継承し、courseTitleという新しいプロパティを追加します。
インスタンスの作成とメソッドの呼び出し
const mattDamon = new studentClass("Matt Damon", 1970, "Astrophysics");
mattDamon.calculateAge(); // 54
mattDamon.introduceSelf(); // My name is Matt Damon and I study Astrophysics
mattDamon.oneLiner(); // Matt Damon will be 55 years old next year.
mattDamonというインスタンスを作成し、メソッドを呼び出して結果を確認します。
Object.createによるプロトタイプ継承
personProtoオブジェクト
Object.createを使ってプロトタイプを継承します。
const personProto = {
calculateAgeNum() {
console.log(currentYear - this.birthYear); // 年齢を計算し、出力します
},
init(firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
},
};
personProtoオブジェクトには、calculateAgeNumメソッドとinitメソッドがあります。
studentProtoオブジェクト
personProtoを継承するstudentProtoオブジェクトを定義します。
const studentProto = Object.create(personProto);
studentProto.init = function (firstName, birthYear, courseTitle) {
personProto.init.call(this, firstName, birthYear);
this.courseTitle = courseTitle;
};
studentProto.introduceYourself = function () {
console.log(`My name is ${this.firstName} and I study ${this.courseTitle}`); // 自己紹介を出力します
};
studentProtoはpersonProtoを継承し、courseTitleプロパティとintroduceYourselfメソッドを追加します。
インスタンスの作成とメソッドの呼び出し
const willSmith = Object.create(studentProto);
willSmith.init("Will", 1968, "International Relations");
willSmith.introduceYourself(); // My name is Will and I study International Relations
willSmith.calculateAgeNum(); // 56
willSmithというインスタンスを作成し、メソッドを呼び出して結果を確認します。
まとめ
本記事では、JavaScriptのオブジェクト指向プログラミングの基本概念を、3つの異なる方法で説明しました。コンストラクタ関数、クラス構文、Object.createによるプロトタイプ継承の各方法について、具体的なコード例を通じて学びました。これらの知識を活用して、より複雑なJavaScriptアプリケーションを構築できるようになるでしょう。
Githubでも公開してるよ!
先ほどのコードはGithubで公開しているよ。
ここ見てね!