組織 JS 程式碼通常以這兩種 patterns 為主軸,classes 和 modules。他們可以同時使用、單獨使用、或者都不使用,當然跟著 pattern 走,會比較清晰。
A class in a program is a definition of a "type" of custom data structure that includes both data and behaviors that operate on that data. Classes define how such a data structure works, but classes are not themselves concrete values. To get a concrete value that you can use in the program, a class must be instantiated (with the new keyword) one or more times. __ https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/get-started/ch2.md#classes
class Flight {
constructor(info) {
this.info = info;
}
print() {
console.log(this.info);
}
}
class AsiaFlights {
constructor() {
this.flights = [];
}
addFlight(flight) {
let flight = new Flight(flight);
this.flights.push(flight);
}
print() {
for (let flight of this.flighs) {
flight.print();
}
}
}
var asiaFlights = new asiaFlights();
asiaFlights.addFlight({'Destination': 'LAX', ... });
asiaFlights.addFlight({'Destination': 'YVR', ... });
asiaFlights.print();
// ...
Flight 這個 class,家族成員是 info,他們共同的行為是 print()。
AsiaFlights 這個 class,家族成員是 flights,他們共同行為是 addFlight(), 和 print()。
回到一開始說的:A class in a program is a definition of a "type" of custom data structure that includes both data and behaviors that operate on that data.
Class 將不同的資料 ( info, flights ) 整理出相同的行為 ( print(), addFlight() )。
接著作者會提到繼承,不過在工作上真的較少遇到,我就留下參考了:
https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/get-started/ch2.md#class-inheritance
今天份的學習到這邊
[ 參考 ]