Class其實不算存在, 頂多是個語法糖; 但我們今天不討論這個< br />
類別(Class)可以透過建構子(constructor)來添加屬性
例如
class Car {
constructor() { // 一個 class 只能有一個 constructor
this.wheels = 4,
this.seats = 4
}
getDetail() {
return [this.wheels, this.seats];
}
}
// 使用
var myCar = new Car();
class NewCar {
constructor(_brand, _color) {
this.brand = _brand,
this.color = _color,
this.year = '2018'
}
}
// 使用
var myCar = new NewCar('CarBrand', 'Red');
如果要用繼承
則加上擴展(extends)
class Bus extends Car {
constructor() {
super(); // 透過super(), 來取得父類別項目
this.seats = 20
}
getDetail() {
return [this.wheels, this.seats];
}
}
要匯出(Export)的話
// Export
module.exports.Car = Car;
module.exports.NewCar = NewCar;
module.exports.Bus = Bus;
使用的話有分import / require
其中的差別又可以寫一篇文章
這邊簡單使用require
// import
var CarModule = require('./carModule');
var smallCar = new CarModule.Car;
var RedCar = new CarModule.NewCar('ZZZ', 'Red');
var myBus = new CarModule.Bus;