3 回答
TA貢獻2003條經驗 獲得超2個贊
嗯... tldr; javascript很古怪!
本質上,在您的第一個片段中:
Assign value of, x = 5;
Assign value of, y = x, which holds a reference to the primitive value 5, so y is now directly 5, not x's reference.
Assign value of, x = 6, direct value again, removes the previous correlation with x and y.
發生上述情況是因為您的分配涉及原始類型。當您說 y=x 時,您將原語 5 分配給 y,而不是對 x 的引用,這正是因為 X 擁有一個原語,而不是一個對象。
另一方面,您的第二種情況涉及對象,而是通過引用傳遞。
因此,在“此處”進行更改實際上會影響指向“此處”的所有引用
x = {one : 5}
y = x -> This now is an assignment by passing the reference value, i.e Y points to the same object X is pointing.
x.one = 6; -> this will actually effect the same reference Y has
更進一步,如果我們現在在哪里再次變異 y 呢?
如果我們在您的第二個示例中將此行作為最后一行
y = { two : 5}
這根本不會影響 X,它只會為 y 重新分配一個全新的對象值。
這與 javascript 如何處理引用和賦值有關。在這里看看ref 叢林的一個不錯的起點
TA貢獻1776條經驗 獲得超12個贊
來自https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing的精彩(截斷)摘錄:
如果一個變量被傳遞[給一個函數],就不可能在被調用者的范圍內模擬對該變量的賦值。但是,由于函數可以訪問與調用者相同的對象(不進行復制),因此調用者可以看到函數內這些對象的突變。
添加回答
舉報

