3.14 類別(Class)
在 javascript/practice
資料夾下,建立 class.html
來練習。
概念
要做杯子蛋糕,就要有做杯子蛋糕的模具(杯子),有了模具(杯子),就可以重覆做出杯子蛋糕。
類別宣告
使用 class
來宣告,以及常搭配 constructor
建構子,以下就是上述概念所說的模具:
class Book {
constructor(book_name, price){
//console.log("hi");
//console.log(this);
this.book_name = book_name;
this.price = price;
}
}
實體化一個書本物件
做出一個書本:
var book1 = new Book("書本名稱一", 300); // 會自動執行 constructor
console.log(book1);
增加功能
替模具增加功能,改成以下(加上 show_discount_price 函式
):
class Book {
constructor(book_name, price){
//console.log("hi");
//console.log(this);
this.book_name = book_name;
this.price = price;
}
show_discount_price(){
return this.book_name + " 特價 " + this.price * 0.9 + " 元";
}
}
使用功能
var book1 = new Book("書本名稱一", 300);
console.log(book1.show_discount_price());
實體化第二個物件
var book1 = new Book("書本名稱一", 300);
var book2 = new Book("書本名稱二", 400);
Last updated