immutable (可变的) 与 immutability (不可变的)

Node.js immutable (可变的) 与 immutability (不可变的)
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);

参考资料