# PixiJS 切換場景(3)Class ###### tags: `PixiJS` 2022.10.23(Sun.) ## ▉ Introduction 為了學習切換場景,所以先看了[奔跑吧!台北:程式幕後分享](https://medium.com/@chiunhau/%E5%A5%94%E8%B7%91%E5%90%A7-%E5%8F%B0%E5%8C%97-%E7%A8%8B%E5%BC%8F%E5%B9%95%E5%BE%8C%E5%88%86%E4%BA%AB-e02d0a565559)的文章,裡面提到了一篇文章「[Tutorial : Handling game scenes and screen scaling with Pixi](http://ezelia.com/2013/pixi-tutorial)」,然後打開來後發現...我在看的程式碼語言是JavaScript嗎?(完全看不懂QQ) ### Keywords 整理一些從[Tutorial : Handling game scenes and screen scaling with Pixi](http://ezelia.com/2013/pixi-tutorial)中看見的Keywords: module, export, class, constructer, super, extends 不過在學習上述關鍵字的路上,碰到了更多的關鍵字...所以決定乘著這個機會,一步步的把他補齊。 **** ## ▉ Class 再來進入到class的部分,總算跟上面的關鍵字有些搭上了QQ 查了一下class,通常都會伴隨著「語法糖」三個字一起出現,所以先來看看語法糖這個名詞到底是甚麼。 ### 語法糖 在維基百科中,他給予語法糖的定義如下: > 語法糖(英語:Syntactic sugar)是由英國電腦科學家彼得·蘭丁發明的一個術語,指電腦語言中添加的某種語法,這種語法對語言的功能沒有影響,但是更方便程式設計師使用。語法糖讓程式更加簡潔,有更高的可讀性。 感覺上就是有一個新的語法,他可以幫助我們比起原先的寫法更加簡潔、擁有更高的可讀性,但是即便沒有這些語法糖,程式仍然可以照舊有的方法進行運作。 可以想像語法糖就是舊有寫法的進化版(?) 而class就是這樣的存在,不過他是哪種寫法的進化版呢? 就是前面提到的Construction Function + new,所以說雖然這個語法叫做class,但他背後的原理仍然是原型prototype,目的是讓我們在使用JS模擬物件功能時,可以更加方便點,不過概念都是相同不變的。 ### 比較 #### 1. Construction Function + new 先來回顧一下Constructor Function 的部分,以下方程式碼為例: ```javascript! function Person(name, age){ this.name = name; this.age = age; } Person.prototype.talk = function(){ return `Hello I am ${this.name}, I'm ${this.age} years old.` } const Jay = new Person("Jay", 20) ``` #### 2. Class + new 如果利用語法糖class的話,則會連同talk method也被包在class裡面,而class裡頭會使用一個constructor()函式將instance實例的屬性包裹起來,並且與Constructor Function一樣,利用new關鍵字來建立新的物件。 因此當用new關鍵字創建新物件時,會立刻執行constructor()。 ```javascript! class Person{ constructor(name, age){ this.name = name; this.age = age; } talk(){ return `Hello I am ${this.name}, I'm ${this.age} years old.` } } const Jay = new Person("Jay", 20) ``` 並且可以發現,第二種方法用class,即使沒使用到.prototype,將talk() method放在class裡頭,便會自動加到Person 的prototype上,如此一來我們可以更清楚的看出整整個class都是一個家族的: ```javascript! class Person{ constructor(name, age){ this.name = name; this.age = age; } talk(){ return `Hello I am ${this.name}, I'm ${this.age} years old.` } } const Jay = new Person("Jay", 20) const Mark = new Person("Mark", 21) ``` ![](https://i.imgur.com/JB9puML.png) 所得到的結果為下 ![](https://i.imgur.com/6SYrryk.png) **** ### 參考資料 * [奔跑吧!台北:程式幕後分享](https://medium.com/@chiunhau/%E5%A5%94%E8%B7%91%E5%90%A7-%E5%8F%B0%E5%8C%97-%E7%A8%8B%E5%BC%8F%E5%B9%95%E5%BE%8C%E5%88%86%E4%BA%AB-e02d0a565559) * [Tutorial : Handling game scenes and screen scaling with Pixi](http://ezelia.com/2013/pixi-tutorial) * [The Web Developer Bootcamp 2022](https://www.udemy.com/course/the-web-developer-bootcamp/) U29:Prototypes, classes, OOP