摘要:JavaScript Function 概述
JavaScript 要學的好,那對function的了解一定要清楚!
這邊概述了function在物件導向上的用法。

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

這邊宣告一個dog類別,類別建構子就是function本身,建構子參數是pName。
類別內如果以this去宣告的函式會成為物件的方法,以上面的例子來看me.jump會是dog物件的方法,而不是dog類別的方法。
以類別名稱宣告的函式會成為該類別的靜態方法,如dog.jump3;而jump2是全域方法,它屬於window,事實上jump2有沒有放在dog類別中一點也沒有關係,只是想提出全域方法是可以在類別中宣告。
除了在dog類別區塊中宣告之外,也可以在類別外宣告方法:

2

3

4

5

6

7

使用protootype來為類別宣告原型方法,dog.prototype.sleep或是dog.prototype['sleep']皆可。使用原型宣告的方法會在程式執行時便載入到類別中,所以prototype的方式為early binding,也就是當執行到dog.prototype.sleep時,dog類別中已經有sleep這個方法,而在dog類別區塊中的me.jump會在new一個dog物件時才會載入,這是因為me.jump在new時才會被接觸到,這算是late binding的方法!dog.eat是dog類別的靜態方法,與sleep一樣算是early binding。這邊的early binding其實有依照程式執行順序而定,切確的說sleep和eat都算是後來被匯入類別的方法!小結一下,到目前為止sleep和jump為dog的public methods,eat和jump3為dog的public static methods,而jump2是global function!






接下來我們直接來看new一個物件後的行為!
這邊new了一個dog物件p,呼叫p.sleep是成功的,因為sleep是dog的方法。再來p.jump3會失敗,因為jump3是靜態方法,需要dog.jump3去呼叫才會成功。最後dog.jump2也會失敗,因為jump2是全域方法,只要直接呼叫jump2即可。
最後我依程式的執行順序來排列方法生成的順序:
1. dog
2. dog:prototype:methods[sleep]
3. dog:methods[eat]
4. p:methods[sleep]
5. dog:prototype:methods[sleep, jump], p:methods[sleep, jump]
6. window:methods[jump2]
7. dog:methods[eat, jump3]
dog:prototype[sleep, jump] - dog類別的方法
dog:methods[eat, jump3] - dog類別的靜態方法
p:methods[sleep, jump] - dog物件p可使用的方法
window:methods[jump2] - 全域函式