LESSON 26 ・ クラス
メソッドと初期化
メソッドを定義する
class Student {
name = "";
score = 0;
show() {
console.log(`${this.name}: ${this.score}点`);
}
}
let student = new Student();
student.name = "Mary";
student.score = 65;
student.show();
クラスにはフィールドだけでなく、クラス専用の関数であるメソッド(method)を定義することもできます。メソッドの中ではthisが自分自身を指します。
ここでは、Mary: 65点のような形式で名前と点数を出力するメソッドshowを実装しています。
student.show()とすると、studentに格納されているStudentオブジェクトに対してshowが呼び出されます。
作成と同時に初期化する
class Student {
constructor(name, score) {
this.name = name;
this.score = score;
}
show() {
console.log(`${this.name}: ${this.score}点`);
}
}
let student = new Student("Mary", 65);
student.show();
constructorは特別なメソッドで、new Student( )でStudentオブジェクトを作成するときに呼ばれます。constructorにパラメータを定義すると、new Student("Mary", 65)のように引数を渡し、オブジェクト作成と同時に指定された値でフィールドを初期化できます。
そうすれば、後からstudent.name = "Mary"のようにして値をセットしなくても、Student("Mary", 65)のようにして初期化できます。
constructorのことをコンストラクタと言います。
PRACTICE
演習問題
コードを自分で書いて実行してから、答えと解説を確認しましょう。
問題1
名前と点数を持つStudentクラスに、名前: 点数点の形で表示するshowメソッドを定義してください。名前が"Mary"、点数が65のオブジェクトでshowを呼び出してください。
答えと解説を見る
模範解答
class Student {
name = "";
score = 0;
show() {
console.log(`${this.name}: ${this.score}点`);
}
}
let student = new Student();
student.name = "Mary";
student.score = 65;
student.show();
メソッドの中では、thisを使って、そのメソッドを呼び出したオブジェクト自身の値へアクセスします。
問題2
題名とページ数を作成時に受け取るBookクラスを定義してください。また、題名: ページ数ページの形で表示するshowメソッドも定義し、"Python Guide"、240で作ったオブジェクトから呼び出してください。
答えと解説を見る
模範解答
class Book {
constructor(title, pages) {
this.title = title;
this.pages = pages;
}
show() {
console.log(`${this.title}: ${this.pages}ページ`);
}
}
let book = new Book("Python Guide", 240);
book.show();
constructorで作成時の引数を受け取り、それぞれの値を初期化しています。
問題3
幅と高さを作成時に受け取るRectangleクラスを定義してください。面積を返すareaメソッドを作り、幅8・高さ5の長方形の面積を表示してください。
答えと解説を見る
模範解答
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
let rectangle = new Rectangle(8, 5);
console.log(rectangle.area());
初期化した幅と高さをareaメソッドで掛け、結果を戻り値にします。rectangle.area()は40を返します。