javascript - Copied object generated by Object.Assign() function has side effect? -
i have object named result composed of 2 objects :
const = {bar: {baz: 2}}; var b = {foo: 1}; var result = object.assign({}, a, b); console.log(result, a, b); // result -> {bar: {baz: 2}, foo: 1} // -> {bar: {baz: 2}} // b -> {foo: 1}
now, changing bar property of result object like:
result.bar.baz = 3; result.foo = 4; console.log(result, a, b); // result -> {bar: {baz: 3}, foo: 4} // -> {bar: {baz: 3}} intresting part // b -> {foo: 1} intresting, too!
(you can copy , paste code javascript console in order see result both cases way)
there 2 weird things here. first 1 changing resulting object's property, constant object a's property changes, too. if first 1 case object.assign function, how can change constant variable? let's case despite const variable mutation, why change in property foo not reflect object b? came because use object.assign copy objects, pretty weird issue function guess. ideas case? thank you.
declaring variable const
prevents being changed value. doesn't prevent data referenced value change.
const foo = {prop: 'bar'}; foo.prop = 'baz'; // works foo = 'baz'; // typeerror: invalid assignment const `foo'
if want prevent object being changed, can freeze it.
object.freeze(foo); foo.prop = 'buz'; // typeerror: "prop" read-only
however, affect own properties. if value of 1 of these object, won't become frozen.
this happens object.assign
too. copies own properties, , if value object, won't "clone" it. is, references still same, , changes reflected.
if want clone object, see what efficient way clone object?
Comments
Post a Comment