[Medium] 📄 Primitive vs Reference Types
1. What are Primitive Types and Reference Types?
什麼是原始型別(Primitive Types)和參考型別(Reference Types)?
JavaScript 的資料型別分為兩大類:原始型別和參考型別。它們在記憶體儲存方式和傳遞行為上有本質的差異。
原始型別(Primitive Types)
特點:
- 儲存在**堆疊(Stack)**中
- 傳遞時複製值本身(Call by Value)
- 不可變的(Immutable)
包含 7 種:
// 1. String(字串)
const str = 'hello';
// 2. Number(數字)
const num = 42;
// 3. Boolean(布林值)
const bool = true;
// 4. Undefined
let undef;
// 5. Null
const n = null;
// 6. Symbol(ES6)
const sym = Symbol('unique');
// 7. BigInt(ES2020)
const bigInt = 9007199254740991n;
參考型別(Reference Types)
特點:
- 儲存在**堆積(Heap)**中
- 傳遞時複製參考(記憶體地址)(Call by Reference)
- 可變的(Mutable)
包含:
// 1. Object(物件)
const obj = { name: 'John' };
// 2. Array(陣列)
const arr = [1, 2, 3];
// 3. Function(函式)
const func = function () {};
// 4. Date
const date = new Date();
// 5. RegExp
const regex = /abc/;
// 6. Map, Set, WeakMap, WeakSet (ES6)
const map = new Map();
const set = new Set();
2. Call by Value vs Call by Reference
傳值(Call by Value)vs 傳址(Call by Reference)
傳值(Call by Value)- 原始型別
行為:複製值本身,修改副本不影響原值。
// 原始型別:傳值
let a = 10;
let b = a; // 複製值
b = 20; // 修改 b
console.log(a); // 10(不受影響)
console.log(b); // 20
記憶體示意圖: