# JS OOP (class相關) ## 繼陳 如果連建構子都要繼承 用super就不用重複寫 ![](https://i.imgur.com/SYGMoWs.png) https://www.youtube.com/watch?v=V4R95_MJN70 Class 只需要利用 extends 和 super 便可輕鬆處理 Constructor 間的 Inheritance ## 多態性 https://www.youtube.com/watch?v=ZrCNeqT3XDw # class https://medium.com/enjoy-life-enjoy-coding/javascript-es6-%E4%B8%AD%E6%9C%80%E5%AE%B9%E6%98%93%E8%AA%A4%E6%9C%83%E7%9A%84%E8%AA%9E%E6%B3%95%E7%B3%96-class-%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95-23e4a4a5e8ed Java 的 Class-Based 物件導向語言,都會知道下面幾件事情: 分成 Class 和 Object 兩種。 Class 內部會描述 Properties 和 Method。 Class 能建構出 Object ,也被稱作 Instance 。 Instance 能夠使用 Class 內的 Method,並藉由 Method 存取 Object 內的資料。 **但是** 擁有 Class 才能產生出對應的 Instance ,這是與 JavaScript 差別最大的地方。 在 JavaScript 的 Prototype-Based 物件導向中,不區分 Class 和 Object 所有的東西都可以是 Object, 且不一定需要經過 Class 或 Constructor 才能建立 Instance,直接操作 Prototype 也能辦到。 **操作** Java 中要做 Class 間的繼承,得在定義 Class 時指定要繼承的父類別。在 JavaScript 中則是以改變 Constructor 的 Prototype 來使用其他 Constructor 的 Method ## 介紹 Class 只是簡化了 JavaScript 中操作 Constructor 的語法糖而已 ## Constructor Constructor 是建構器,可以用它產生擁有相同 Properties 的 Object ``` function Person(name) { // public properties this.name = name; // private value const state = 'Taiwan'; // privileged methods this.getFrom = () => `${this.name} from ${state}.`; } const john = new Person('John'); console.log(john); // { name: 'John', getFrom: [Function] } console.log(john.state); // undefined console.log(john.getFrom()); // John from Taiwan. ``` * name 是經過 Person 創建出來後會帶的 Own Properties (自有特性),會在呼叫 Constructor 時當作參數傳入。 * state 是一個 Private value (私有值),它只存在於 Constructor 創建 Instance 時另外產生的環境。 * 雖然 state 不是 Instance 的 Own Properties ,但是透過 getForm 便能夠取得 state 的值,這種讀取 Private value 的方式稱作 Privileged Method (特權方法)。 ## ES6 時期的 Constructor Class 來宣告 Constructor 在語義上面會更清楚,不像之前只能透過字首的大小寫來判斷是否為 Constructor ,且還有可能會有未遵照規則導致使用錯誤的情況發生 ``` class Person { constructor(name) { this.name = name; } getFrom() { const state = 'Taiwan'; return `${this.name} from ${state}.`; } } const john = new Person('John'); console.log(JSON.stringify(john)); // { name: 'John' } public 方法不再顯露於物件裡 console.log(JSON.stringify(john.state)); // undefined console.log(JSON.stringify(john.getFrom())); // John from Taiwan. ``` new 呼叫時傳入的參數會由 Class 內的 constructor 給接收,並在同一區塊建立 Public Properties ,而 Method 的部分則是在 constructor 外做描述或存取資料, Private Value 就存放在 Method 中,依然無法從 Instance 中取得。 ###### tags: `javaScript`