LESSON 25 ・ クラス
クラス
情報がばらばらになる問題
let names = ["Mary", "Mike", "Tom"];
let scores = [65, 90, 85];
for (let i = 0; i < names.length; i += 1) {
console.log(names[i], scores[i]);
}
複数人の名前とテストの点数を扱うには、二つの配列が必要になります。しかし、名前と点数をばらばらに扱うことになりわかりづらいです。
クラスで情報をまとめる
class Student {
name = "";
score = 0;
}
let student = new Student();
student.name = "Mary";
student.score = 65;
console.log(student.name);
console.log(student.score);
クラス(class)を使えば、名前と点数のような、複数種類の値を一つにまとめて扱うことができます。
ここではStudent(生徒)クラスを作ります。Studentクラスはnameとscoreの二つのフィールド(field)を持っています。
new Student()でStudentのオブジェクトを作って変数studentに代入します。student.nameやstudent.scoreのように、オブジェクトを格納した変数名とプロパティ名を.でつなぐことで、フィールドの値にアクセスすることができます。
class Student {
name = "";
score = 0;
}
let student = new Student();
student.name = "Mary";
student.score = 65;
console.log(`${student.name}: ${student.score}点`);
Mary: 65点のような形式で名前と点数を出力するにはconsole.log(`${student.name}: ${student.score}点`)と書けます。
PRACTICE
演習問題
コードを自分で書いて実行してから、答えと解説を確認しましょう。
問題1
名前と点数を持つStudentクラスを作ってください。オブジェクトを一つ作り、名前に"Mary"、点数に65を代入して、両方を表示してください。
答えと解説を見る
模範解答
class Student {
name = "";
score = 0;
}
let student = new Student();
student.name = "Mary";
student.score = 65;
console.log(student.name);
console.log(student.score);
クラスに名前と点数をまとめ、作成したオブジェクトのそれぞれの値へ.を使ってアクセスします。
問題2
本の題名とページ数を持つBookクラスを作ってください。オブジェクトを一つ作り、題名に"Python Guide"、ページ数に240を代入して表示してください。
答えと解説を見る
模範解答
class Book {
title = "";
pages = 0;
}
let book = new Book();
book.title = "Python Guide";
book.pages = 240;
console.log(book.title);
console.log(book.pages);
関連する題名とページ数を一つのBookオブジェクトにまとめています。
問題3
幅と高さを持つRectangleクラスを作ってください。幅8・高さ5のオブジェクトと、幅3・高さ9のオブジェクトを作り、それぞれの面積を表示してください。
答えと解説を見る
模範解答
class Rectangle {
width = 0;
height = 0;
}
let first = new Rectangle();
first.width = 8;
first.height = 5;
let second = new Rectangle();
second.width = 3;
second.height = 9;
console.log(first.width * first.height);
console.log(second.width * second.height);
同じクラスから複数のオブジェクトを作ると、それぞれが別の幅と高さを持てます。面積は順に40と27です。