[JavaScript]クラスの書き方(クラスの継承・メソッドのオーバーライド)
[JavaScript]クラスの書き方(クラスの継承・メソッドのオーバーライド):
・JavaScriptのクラスの書き方に慣れる
・忘れた時に確認する
JSでWEBページに動きを与える・動的にHTMLを書き換えることはしたけど、クラスの継承・メソッドのオーバーライドも書けるとは思わなかった。
この記事を書く目的
・JavaScriptのクラスの書き方に慣れる・忘れた時に確認する
JavaScriptのクラス
sample.js
class Sample{
constructor(a,b){
this.a = a;
this.b = b;
}
getA(){
return this.a;
}
getB(){
return this.b;
}
//クラスの継承
class Subsample extends Sample{
constructor(a,b,c,d){
super(a,b);
this.c = c;
this.d = d;
}
getC(){
return this.c;
}
getD(){
return this.d;
}
}
}
サンプル
sample.js
class Product{
constructor(name,price){
this.name = name;
this.price = price;
}
info(){
console.log(`商品名:${this.name} ${this.price}円`);
}
}
//フード
class Food extends Product{
constructor(name,price,calorie){
super(name,price);
this.calorie = calorie;
}
info(){
console.log(`商品名:${this.name} ${this.price}円 ${this.calorie}kcal`);
}
}
//ドリンク
class Drink extends Product{
constructor(name,price,amount){
super(name,price);
this.amount = amount;
}
info(){
console.log(`商品名:${this.name} ${this.price}円 ${this.amount}ml`);
}
}
//商品
const onigiri = new Food('おにぎり',108,100);
const bread = new Food('パン',216,200);
const greentea = new Drink('緑茶',141,500);
const coffee = new Drink('コーヒー',108,300);
const book = new Product('雑誌',860);
const newspaper = new Product('新聞',180);
const products = [onigiri,bread,greentea,coffee,book,newspaper];
//商品の一覧表示
for(let i=0;i<products.length;i++){
products[i].info();
}
出力結果
商品名:おにぎり 108円 100kcal 商品名:パン 216円 200kcal 商品名:緑茶 141円 500ml 商品名:コーヒー 108円 300ml 商品名:雑誌 860円 商品名:新聞 180円
コメント
コメントを投稿