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
主题 StackJimmy 设计