iT邦幫忙

2022 iThome 鐵人賽

DAY 12
0
自我挑戰組

I don't know JS yet系列 第 12

[ Day 12 ] I don't know JS yet - Class & Modules

  • 分享至 

  • xImage
  •  

組織 JS 程式碼通常以這兩種 patterns 為主軸,classesmodules。他們可以同時使用、單獨使用、或者都不使用,當然跟著 pattern 走,會比較清晰。

Class

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

Highlight

  1. Class 可以想成是同血緣的家人,彼此之間會有相同的習慣,但又各自擁有另一套自己的習慣,不變的是他們的血緣關係
  2. Class 必須使用 new 來初始化,才可以使用
    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

今天份的學習到這邊

[ 參考 ]


上一篇
[ Day 11 ] I don't know JS yet - Comparisons Part 1
下一篇
[ Day 13 ] I don't know JS yet - Class & Module ( part 2 )
系列文
I don't know JS yet30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言