分配时
x
到
obj.speed
,这与为基元变量赋值类似。
如果指定的值为
obj
to变量
y
,然后它将被更新,因为它将引用相同的内存位置。
var obj = {
car: "volvo",
speed: 20
};
// Object is a referece data type.
// But you are assigining value of obj.speed which is primitive to the the x
// Hence value of x won't change even if you change the value of obj.speed.
var x = obj.speed;
obj.speed = 500;
console.log(x);
// But if you assign the value of object to another variable `y`
// Now, y will be pointing to the same memory location as that of obj
// If you update the obj, then the value of y will also get updated
var y = obj;
obj.speed = 1000;
console.log(y);
console.log(obj);