iT邦幫忙

0

JS 物件的參考特性 DAY59

JS 在將值賦予到變數上時
會有兩個特性(Call by value(傳值) 與 Call by reference(傳參考))

// 傳值
var name1 = '皮傑先生';
var name2 = name1;
name2 = '小雞公主'
console.log(name1 , name2); // 皮傑先生 小雞公主
// 傳參考
// 假設此物件位址為 0x01
var person = {
    name : '皮傑先生',
}

// 傳參考 0x01的位址傳給 person2
// person2 與 person 皆指向位址為0x01的物件
var person2 = person;

// 這裡修改0x01 當然因為 person2 與 person 皆指向位址為0x01的物件 , 所以 person 也會被修改
person2.name = '小雞公主';
console.log(person , person2); // 小雞公主 小雞公主
console.log(person === person2); // true
// 傳參考
var person = {
    name : '皮傑先生1',
}
var person2 = person;
person2 = {
    name : '皮傑先生2',
};
console.log(person , person2);

// 兩者參考位置不同
console.log(person === person2); // false

我們來看一下比較複雜的例子

物件參考實際運作模式

var a = { x : 1};
var b = a;
a.y = a = { x : 2};
// a = { x : 2} 是一個運算式
// a.y = a = { x : 2} 同時執行
// a.y 找的是原本的參考路徑
console.log(a.y);
console.log(b);
console.log(a === b.y);

分解如下
https://ithelp.ithome.com.tw/upload/images/20201020/20123039LdhefwE8hk.jpg

https://ithelp.ithome.com.tw/upload/images/20201020/201230392XoEaDkMvV.jpg

我們再來看一題

var a = { x: 1};
var b = a;
a.x = { x: 2};
a.y = a = { y: 1};
console.log(a); // 結果?
console.log(b); // 結果?

分解如下
https://ithelp.ithome.com.tw/upload/images/20201020/20123039kHUruf2t2n.jpg

https://ithelp.ithome.com.tw/upload/images/20201020/20123039d2WhLlDb5N.jpg

那今天的介紹就到這裡
若有任何問題 或 內容有誤
都可以跟我說唷/images/emoticon/emoticon41.gif


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言