クラスとインスタンス
実践JavaScript / 全 5 枚
実践JavaScript - クラスとインスタンス
作品の設計図を class で書く
作品1件は、タイトルとタグというデータと、表示用の文字を作る処理でできています。この組み合わせを毎回ばらばらに書くかわりに、class で1つの設計図にまとめます。new を書くと、その設計図から実物が1つ作られます。
class そのものは設計図なので、書いただけでは何も存在しません。実物が現れるのは new を書いた瞬間です。
constructor が受け取った値を this に置き、label がその this を読んでいます。
class Work {
constructor(title, tag) {
this.title = title;
this.tag = tag;
}
label() {
return this.title + " / " + this.tag;
}
}
const work = new Work("ECサイト", "React");
console.log(work.label()); // ECサイト / React1 / 5
← → キーでも送れます