文章目錄
前言
2020 二月訂閱 Dan Abramov 的 “Just JavaScript” email。 其使用的文字;圖像譬喻平易近人,重新建立 javaScript 紮實的心智模型:
We will gradually build (or, possibly, rebuild) your mental model of JavaScript to be accurate and useful. A good mental model will help you find and fix bugs faster, understand other people’s code better, and feel confident in the code you write.
2022 再回頭看,這些基本卻重要的觀念值得拿出來分享、再複習。也可以跟 2019 年 008天重新認識 JavaScript 這本書裡的內容相互呼應。
後來這一系列 email 成爲付費線上課程:Just JavaScript
The JavaScript Universe
Values
There are values, and then there’s everything else. We can think of values as different things “floating” in our JavaScript universe. They don’t exist inside our code, but we can refer to them from our code.
Types of Values
value 分爲 Primitive Values (基本型別)、 Objects and Functions (物件型別) 這兩大類。
Primitive Values (基本型別)
再細分爲以下 7 種
- Undefined (undefined), used for unintentionally missing values.
- Null (null), used for intentionally missing values.
- Booleans (true and false), used for logical operations.
- Numbers (-100, 3.14, and others), used for math calculations.
- Strings (“hello”, “abracadabra”, and others), used for text.
- Symbols (uncommon), used to hide implementation details.
- BigInts (uncommon and new), used for math on big numbers.
Objects and Functions (物件型別)
再細分爲以下 2 種
- Objects ({} and others), used to group related data and code.
- Functions (x => x * 2 and others), used to refer to code.
No Other Types, 就以上這 9 種類型了,夠單純~ 😎
In JavaScript, there are no other fundamental value types other than the ones we have just enumerated.
『幻覺案例』。是 『基本型別』,卻會有『屬性』/ 『方法』可以呼叫?
"hi".toUpperCase()
讓 "hi"
這個 String 看起來像是 Object 才會出現的行爲。
原因是:JavaScript creates a wrapper object when you do this, and then immediately discards it.
008天重新認識 JavaScript 補充:
內建物件
-
Array()
-
Object()
-
Function()
-
RegExp()
-
Date()
-
Error()
-
Symbol()
-
Math() 並非建構式,所有的屬性都是唯讀的,無法產生新物件
|
|
這三個看起來很像基本型別的東西,就算透過 new 來建立的值,依然是『物件』:
|
|
爲什麼
str
明明是 『基本型別』,卻會有『屬性』/ 『方法』可以呼叫?
因爲:當我們嘗試要去存取 String / Number / Boolean 這三種基本型別的屬性時候,它就只會在當下的『那一刻』(runtime) 被『轉型』爲該類別的物件。
Expressions
Expressions are questions that JavaScript can answer. JavaScript answers expressions in the only way it knows how — with values.
Expressions always result in a single value.
觀念小測驗
typeof 的 bug
typeof(null) // "object"
typeof(null) is “object” even though null is not an object. Null is a primitive value. (Here’s a historical note on how that happened.) This is a very old bug in JavaScript. It cannot be fixed because it would break existing websites.