Try   HackMD

物件傳參考特性|筆記 by Jiang

tags: Jiang Vue新手夏令營

物件傳參考特性

一般物件賦值到一個變數上,其實是傳參考方式,物件是一樣的:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


// #1 物件是以傳參考的形式賦值
const person = {
  name: '小明',
  obj: {}
}

const person2 = person;
person2.name='杰倫';
// console.log(person2 === person); // true
// console.log(person2 , person); // 兩個 name 一起變杰倫

// 物件陣列函式都是傳參考的特性,不會直接寫在原本記憶體位置,而會建立新的記憶體空間

const obj2 = person.obj;
obj2.name='物件下的名稱';
console.log(person);

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

所以像上面的code,當改了 person2.name 時,其實原本 person.name 也會改到,因為他們本就是指向同一個物件記憶體空間。

const fn = (item) => {
  item.name = '杰倫';
}
const person = {
  name: '小明',
  obj: {}
}
fn(person.name);//杰倫

function傳參數方式改也會影響到同一個物件


淺層拷貝&深層拷貝兩種方式:

淺層拷貝有兩個方法:

  1. Object.assign()
  2. {...物件名稱}

淺層拷貝

// #3 解決方案
// #3-1 淺層拷貝
const person = {
  name: '小明',
  obj: {}
}

const person2 = Object.assign({}, person); //空物件,把 person 傳進來,把值傳到 obj
const person3 = {
  ...person  // 展開
}
console.log(person === person2,person === person3); // false false
person2.obj.age=16;
console.log(person,person2); 
// 淺層拷貝只會複製第一層的內容,第二層的內容指向原有的參考,所以第二層有修改,原本的物件會被影響

淺拷貝只有第一層屬性有另外拷貝出來,
後面層數的屬性值都還是參考原物件屬性的,
代表改 person2.obj 時,person.obj 也會被改動到。

深層拷貝

深層拷貝:先用 JSON.stringify() 轉為字串,
再用 JSON.parse() 轉回物件,完整拷貝

const person2 = JSON.parse(JSON.stringify(person));
// 先將物件轉為字串 再把字串轉物件
// console.log(person2);
person.obj.age=16;
console.log(person2,person);

只能拷貝純資料,物件函式無法

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →