javascript对象属性不同对象之间的赋值

javascript object property assignment between different objects

我读了一个片段,很困惑,找不到规则或原则来解释,输出是 Malibu,为什么不是 London let john = { surname: 'Watson', address: sherlock.address }; 中的 adress: sherlock.address =]是把sherlock.adress的值赋给john.address,但不会用john.address覆盖sherlock.adress。我头发怎么会fiddle

let sherlock = {
  surname: 'Holmes',
  address: { city: 'London' } 
};
let john = {
  surname: 'Watson',
  address: sherlock.address
};
john.surname = 'Lennon';
john.address.city = 'Malibu';
console.log(sherlock.address.city); //

关于对象的令人困惑的事情是 PRIMITIVES 的行为与 OBJECTS 不同

当您“读取”原始字符串(或数字或布尔值)时,例如 sherlock.surname,您正在获取它的 value,即您正在接收原始数据的副本。所以如果你这样做

eureka = {surname: sherlock.surname}

那么你可以想到 eureka 收到原版“福尔摩斯”的“复印件”。您的计算机中将存储两个字符串“福尔摩斯”。一个可以改,另一个不会改,因为它们是分开的。

但是当你“读取”一个对象,比如sherlock,你应该想象你只是一个指向原始对象的指针对象。不是它的副本,而是通过计算机到达相同内存位置的另一条路径。所以如果你这样做

eureka = sherlock

然后该语句不会在计算机中创建字符串“Holmes”的第二个副本。计算机的内存中只有一个“福尔摩斯”字串。它在这样一个对象中:{surname: "Holmes"}sherlock 指向那个对象,eureka 指向同一个对象。因此,当你编辑eurekasherlock中的某些属性时,两个变量对应的属性会同时改变。 eurekasherlock 这两个变量名称指向内存中的同一个对象。

以上是非常基本的(请原谅我的双关语!)但是当您引用对象中的对象或对象中的原始对象时,它会变得棘手。单看赋值语句你无法判断你正在阅读的东西是原始类型还是对象。必须知道结构才能知道

let a={b:{c:1}}

let w = a // This makes "w" an alias for the same single object, to which "a" also points

w.b.c=2
console.log(a)
// {
//  "b": {
//    "c": 2
//  }
// }

w.b = 3
console.log(a)
// {
//  "b": 3
// }

在此处注释您的脚本

let sherlock = {
  surname: 'Holmes',
  address: { city: 'London' } 
};
let john = {
  surname: 'Watson',
  address: sherlock.address // Here, you are not COPYING the { city: 'London'}, you are pointing at the same object in memory, i.e. the "address" property of sherlock.
};

john.surname = 'Lennon';
john.address.city = 'Malibu'; // When you go to john.address, you are now pointing into the piece of memory that sherlock is also using to store his address, so when you put a value into 'city', that will show up whether you access it as john.address or sherlock.address

console.log(sherlock.address.city);