Why doesn't the change edit the object referenced by obj?
Since inside change when writing:
obj = {b:2}
Note that obj is a local variable for calling the modify function. A new object {b:2} , and the local variable obj now refers to this new object. Recall that the variable x still refers to the object {a:1} .
If x is a global variable AND, if a local variable is not specified inside the function, you can do:
var x = {a:1}; function modify() { x = {b:2} } modify(); console.log(x)
Why does this code work?
When you call modify () , it tries to see if it has a local variable x, since it cannot find it, it scans the chain of scopes. The next area to search for this function call is the global area, and, of course, we have the variable x . Therefore, this global variable x is now set.
source share