Very simple js variable difficulty, who can make me understand

var a = {name:"1"}
function fn(obj){
    obj.name = "2";
    obj = {name:"3"};
}
fn(a);
a.name  // "2"

Why is the output 2

Mar.28,2021

var a = {name: "1"} lets the variable a refer to an object in memory {name: "1"} . When fn (obj) is called, the variable obj references {name: "1"} , and then executes obj.name = "2"; modifies the name property of the reference object.
obj = {name: "3"}; lets the variable obj refer to a new object in memory {name: "3"} .


what was said upstairs is not detailed enough.

clipboard.png
here refers to arguments . Before assigning obj , obj , that is,

.
arguments[0]

is always a reference to a . The assignment breaks the reference chain and reassigns a reference to obj , that is, a new object {name:'3'}

.
Menu