# `static` 是什麼? 根據英文說明,`static` 的定義大致如下: > We can also assign a method to the class as a whole. Such methods are called static. 如果直接翻譯的話,大概會是這個樣子: > 我們可以將一個「method 方法」指定(賦值)給一個 `class`,而這樣的 method 我們稱作 **static 靜態**。 看不懂的話也沒關係,因為我也看不懂! ## 用白話文瞭解 `static` 實際上 `static` 是 JavaSript 的一個關鍵字,而它的用途就是將一個 method 或是 property 改變為靜態 `static` 的狀態,更精準地說:「static 是一種用於==宣告靜態方法和靜態屬性的關鍵字==」。 通常這樣的 method 與 property 又可以稱作 **static method 靜態方法**與 **static property 靜態屬性**。 到這邊如果還看不懂,一切正常!我們接續看下去。 ## static method 靜態方法 首先我們看下一面這一段程式碼,是一個很簡單的 `class` 類別的創建。 ```javascript= class greeting { hi() { console.log("hi") } } ``` 假設此時我們想要使用 `class greeting` 裡 `hi` 方法印出 `"hi"`,通常我們會怎麼做? 如果我們使用 `greeting.hi()` 的話,會得到 `greeting.hi is not a function`。 原因是因為此時 `greeting` 只是一個 class 類別的原型,如果我們想要使用 `hi` 方法,首先我們需要先創建一個 `greeting` 的實例 instance,才能使用(調用) `hi` 方法。 作法如下: ```javascript= class greeting { hi() { console.log("hi") } } // 以 class greeting 為原型,使用 new 創建實例 greetingA const greetingA = new greeting() // 此時就可呼叫 greetingA 身上的 hi 方法 greetingA.hi() // hi ``` 回過頭來看,那真的沒有任何辦法可以直接調用 `class greeting` 的 `hi` 方法嗎? 這時候就該派上 `static` 了! ```javascript= class greeting { static hi() { console.log("hi") } } greeting.hi() // hi // 順便想一下,下面這段會印出什麼? const greetingA = new greeting() greetingA.hi() ``` 那可能會問「為什麼不一開始使用 `static` 就好了?」 我們回頭看一下程式碼的 9-11 行,此時的 `greetingA.hi()` 會得到錯誤訊息 `TypeError: greetingA.hi is not a function`。 所以這邊可以歸納出幾件事: - 靜態方法 static method ==只能==在 class 類別本身被調用。 - 靜態方法 static method ==無法==在 instance 類別實例化中被調用。 - 一般方法 method ==只能==在 instance 類別實例化中被調用。 ## static property 靜態屬性 瞭解了前面 static method 的說明,接著來看 static property,我們直接來思考下列程式碼的結果會是什麼呢? ```javascript= class today { static weather = 'It is sunny.' } console.log(today.weather) // 請問這邊會印出什麼? const anotherDay = new today() console.log(anotherDay.weather) // 請問這邊又會印出什麼? ``` 想當然爾,因為 `static weather` 是靜態屬性,所以可以直接訪問到`weather`,也就是說 `console.log(today.weather)` 會印出 `'It is sunny.'`。 而 `anotherDay` 由於是實例化的類別,所以無法訪問到 `weather`,也就是說 `console.log(anotherDay.weather)` 會得到 `undefined`。 --- **參考資料** > - [简单理解 JS Class 中的 Static 是什么](https://juejin.cn/post/7295943233741324326) > - [JavaScript static 关键字是干嘛的?](https://juejin.cn/post/6940556583482949663)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up