相關文件參考:MDN
Primitive type
immutable, call by value
口訣:UBBNNSS
U:Undefined,變數沒被assigned value時,為undefined
B:Boolean
B:BigInt (少遇到...)
N:Null,null用於表示該object value為空(有被assigned一個value為"null",不是undefined)
N:Number
S:String
S:Symbol,屬於創建後唯一且不可被改變的原型值,不適用new Symbol(" your_symbol ")
// Here are two symbols with the same description:
let Sym1 = Symbol("Sym")
let Sym2 = Symbol("Sym")
console.log(Sym1 === Sym2) // returns "false"
// Symbols are guaranteed to be unique.
// Even if we create many symbols with the same description,
// they are different values.
非Primitive type的,就是Object type
a value in memory, call by reference
call by reference在JavaScript指的是call記憶體位置
所以當copy by reference時,由於y也是指向x的記憶體位置
當y在不創建新Object占用新的記憶體位置的情況下,進行數值變動
此時x的值顯示也會跟著變動,因為x、y同個reference(記憶體位置)
const x = { apple: "$40" };
const y = x;
y.apple = "$20";
console.log(x); //{ apple: '$20' }
但假如y是以創建新Object的方式,x是不會被變動的(記憶體位置所存的值沒被修改到)
const x = { apple: "$40" };
var y = x; //其實這一行結果上是冗的
y = { apple: "$20" };
console.log(x); //{ apple: '$40' }
測試是否搞懂了(source)
//題目
function changeStuff(a, b, c) {
a = a * 10;
b.item = "changed";
c = { item: "changed" };
}
var num = 10;
var obj1 = { item: "unchanged" };
var obj2 = { item: "unchanged" };
changeStuff(num, obj1, obj2);
//請開始你的表演
console.log(num);
console.log(obj1.item);
console.log(obj2.item);
Answers
10 changed unchanged