【Vue3】物件傳參考特性

Vue3

【Vue3】物件傳參考特性

Vue3


兩個物件互相影響

1
2
3
4
5
6
7
8
9
const fruits = {
  name: "蘋果",
  obj:{}
}

const fruits2 = fruits;
fruits2.name = "香蕉";
console.log(fruits.name); //香蕉
console.log(fruits2.name); //香蕉

當物件賦予到另一個物件時,就等於指向同一個物件


兩個物件互相影響2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const fruits = {
  name: "蘋果",
  obj:{}
}

const fn = (item) => {
  item.name = "香蕉";
}

fn(fruits);
console.log(fruits.name); //香蕉

當物件賦予到另一個物件時,就等於指向同一個物件


淺層拷貝(兩物件不影響)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const fruits = {
  name: "蘋果",
  obj:{}
}

const fruits2 = Object.assign({},fruits);

fruits2.name = "香蕉";
console.log(fruits.name); //蘋果
console.log(fruits2.name); //香蕉

fruits2.obj.price = 80;
console.log(fruits.obj.price); //80
console.log(fruits2.obj.price); //80

淺層拷貝的意思是,物件第一層指向不同,但下一層指向卻還是相同


淺層拷貝(兩物件不影響)2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const fruits = {
  name: "蘋果",
  obj:{}
}

const fruits2 = {
  ...fruits
}

fruits2.name = "香蕉";
console.log(fruits.name); //蘋果
console.log(fruits2.name); //香蕉

fruits2.obj.price = 80;
console.log(fruits.obj.price); //80
console.log(fruits2.obj.price); //80

淺層拷貝的意思是,物件第一層指向不同,但下一層指向卻還是相同


深層拷貝(兩物件不影響)

1
2
3
4
5
6
7
8
9
const fruits = {
  name: "蘋果",
  obj:{}
}

const fruits2 = JSON.parse(JSON.stringify(fruits));
fruits2.name = "香蕉";
console.log(fruits.name); //蘋果
console.log(fruits2.name); //香蕉

當物件賦予到另一個物件時,就等於指向同一個物件

Vue3 

其他相關