クラスを使う背景
このように同じ情報を持った複数のオブジェクトがあると書きづらくごちゃごちゃする。
const tanaka = {
lastName: 'tanaka',
firstName: 'taro'
}
const suzuki = {
lastName: 'suzuki',
firstName: 'jiro'
}
const sato = {
lastName: 'sato',
firstName: 'saburo'
}
クラスとは何か
だから使いまわせる情報を持った型のようなものを持っておく。
これがクラス。
class Profile{
constructor(lastName, firstName){
this.lastName = lastName;
this.firstName = firstName;
}
}
インスタンスとは何か
雛形となるクラスを用いて新しく(new)作った情報がインスタンス。
class Profile{
constructor(lastName, firstName){
this.lastName = lastName;
this.firstName = firstName;
}
}
//インスタンスの生成
const tanaka = new Profile('tanaka', 'taro');
console.log(tanaka.lastName)
//tanaka
console.log(tanaka.firstName)
//taro
Dataの時もDateというクラスを元にインスタンスを作っていく。
Dataオブジェクトと言いながら実はクラス。
const noe = new Date()
クラスの継承
lastNameとfirstNameの情報を持つProfileクラス。
この二つの情報に年齢と出身地の情報を加え、自己紹介できるようにしたいとする。
その場合はProfileクラスを拡張して新しいクラス'myProfile'を作る。
これがクラスの継承である。
//クラスの生成
class Profile{
constructor(lastName, firstName){
this.lastName = lastName;
this.firstName = firstName;
}
}
//クラスの継承
class myProfile extends Profile {
constructor(lastName, firstName, age, placeOfBirth){
super(lastName, firstName);
this.age = age;
this.placeOfBirth = placeOfBirth;
}
introduce() {
console.log(`私の名前は${this.lastName}です。年齢は${this.age}歳で${this.placeOfBirth}出身です。`);
}
}
const takashi = new myProfile('田中','たけし',100, '東京');
takashi.introduce();
//私の名前は田中です。年齢は100で東京出身です。
メモ:
スーパークラスは元々のクラスのメソッドも利用できる