简体   繁体   中英

Weird behaviour of Object.assign

I recently tried some luck with Spread Syntax in JavaScript, where the results were weird and crazy enough to post this question. My assumptions about Spread Syntax is that it is similar to Object.assign() , but will it vary with the variables of same nature?

 a = {a: "a"}; b = {b: "b"}; c = {c: "c"}; d = {d: {e: "e"}}; d = Object.assign(a, b, c, d); e = { ...a, ...b, ...c, ...d }; console.log("Before Variable Change"); console.log(d); console.log(e); aa = "s"; bb = "t"; dde = "f"; console.log("After Variable Change"); console.log(d); console.log(e); 
 .as-console-wrapper {max-height: 100% !important; height: 100% !important;} 

What I have got as a result is:

Before Variable Change
{
  "a": "a",
  "b": "b",
  "c": "c",
  "d": {
    "e": "e"
  }
}
{
  "a": "a",
  "b": "b",
  "c": "c",
  "d": {
    "e": "e"
  }
}
After Variable Change
{
  "a": "s",
  "b": "b",
  "c": "c",
  "d": {
    "e": "f"
  }
}
{
  "a": "a",
  "b": "b",
  "c": "c",
  "d": {
    "e": "f"
  }
}

I could understand that de 's value will always change because of its "object" nature and they are mutable, so accepted. But when I tried using the ... spread syntax with this, the first value of the object is changed ( aa ) but not the second one ( bb ) . Am I missing something here?


Extra Info:

Checked with Browsers:

  • Chrome on macOS, Version 71.0.3578.98 (Official Build) (64-bit)
  • Chrome on Windows, Version 70.0.3538.110 (Official Build) (32-bit)

The Object.assign() function changes the content of the first object parameter, which is a . That's also the return value, so after the first Object.assign() call that sets the value of d , it'll be true that d === a .

Thus the assignment of "s" to aa will also change da because d and a reference the same object.

Just adding my two cents, in a simple way:

In other words, the spread operator does this:

d = Object.assign({}, a, b, c, d);
e = { ...a, ...b, ...c, ...d };

Now both the above are same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM