Featured image of post 【JavaScript 變數】immutable (可變的) 與 immutability (不可變的)

【JavaScript 變數】immutable (可變的) 與 immutability (不可變的)

【JavaScript 變數】immutable (可變的) 與 immutability (不可變的)

Photo by Mohammad Rahmani on Unsplash

let Employee = {};
let directCopyEmployee = Employee;
let assignDirectoryCopyEmployee = directCopyEmployee = { name: 'Kay' };
assignDirectoryCopyEmployee.age = 17;

// {}
console.log(Employee);
// { name: 'Kay', age: 17 }
console.log(directCopyEmployee);
// { name: 'Kay', age: 17 }
console.log(assignDirectoryCopyEmployee);

directCopyEmployee 原本是指向 Employee,但後來指向了一個新的物件,所以這兩個就變成指向不同的物件了

而物件是 call by reference,所以修改了 assignDirectoryCopyEmployee 會影響到 directCopyEmployee,因為兩個是指向同一個物件的記憶體位置

物件是 Mutable (可變的)

指向同個物件(同個記憶體位置)的變數,是 傳址 (call by referene),會互相影響,所以是 Mutable 可變的

好處是可以共享記憶體位置節省記憶體的空間

基本型態的資料都是 Immutable (不可變的)

基本型態的資料是 Primitive types,所以是直接 傳值 (call by value)

每次指派都會 分配新的記憶體位置,在記憶體位置上儲存值。

賦值後如果有任何改變(例如:新增、修改、刪除),不會直接更動記憶體上的資料,而是回傳一個新值,所以是 Immutable 不可變的

let Employee = 'Kay,Jay,KJ';
let CopyEmployee = Employee;
let NewSubstrEmployee = Employee.substr(0, 3);
let NewSplitEmployee = Employee.split(',');

// 修改不會影響到原有的變數
CopyEmployee = 'KJ';

// Kay,Jay,KJ : 原始 Primitive types 變數不會有任何的異動
console.log(Employee);
// KJ
console.log(CopyEmployee);
// Kay
console.log(NewSubstrEmployee);
// [ 'Kay', 'Jay', 'KJ' ]
console.log(NewSplitEmployee);

參考資料

Donate KJ 贊助作者喝咖啡

如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method 贊助 Donate
PayPal https://paypal.me/kejyun
綠界 ECPay https://p.ecpay.com.tw/AC218F1
歐付寶 OPay https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8
All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy