Here's what happens:
- The string
"changed" is assigned to the variable foo - The value
foo assigned to obj.prop2 - Since this value is a string (unlike an array, an object),
obj.prop2 just gets the value. It does not receive a link to foo, because these types of values ββ(string, integer, boolean) can be stored in obj as is.
Now try the same thing with a different type:
var bloop = [1, 2, 3]; obj.prop4 = bloop; console.log(obj.prop4); // [1, 2, 3] bloop.push(4); console.log(bloop); // [1, 2, 3, 4] console.log(obj.prop4); // [1, 2, 3, 4]
In this case, what we assign to obj.prop4 is not a value of type string, integer or boolean. Instead, we assign a reference to an array stored elsewhere in memory. bloop and obj.prop4 both contain a reference to the same array in memory, so if the array is updated, both will be updated.
This works both ways:
obj.prop4.push(5); console.log(obj.prop4); // [1, 2, 3, 4, 5] console.log(bloop); // [1, 2, 3, 4, 5]
So, if you are dealing with values ββsuch as string, ints, booleans, you cannot change the properties of the object as you describe. It will work only when the property of the object is a reference to an array, object, etc.
source share