-2

how can I achieve below things in javascript

var parent = {
  a: 5,
  b: 6
}

var child = parent;
console.log(child.b); // 6

//now if I change the value of b
parent.b = 7

console.log(parent.b); //7
console.log(child.b); //7

//but I want to preserve the previous value of the object property it should not change now.it should show 6 instead of 7 in case of console.log(child.b)

https://codebunk.com/b/696347863/

18
  • 2
    Your code has nothing to do with inheritance or prototypes. Commented Jul 9, 2019 at 10:51
  • 2
    @Lain - That's an extremely poor way to duplicate an object. It fails in lots of ways and makes a completely unnecessary pass through text. Commented Jul 9, 2019 at 10:53
  • 2
    @Ele - Based on what the OP says they want (assigning to parent.b not to affect the value of child.b), cloning the object rather than just referring to it is the real problem. The OP's mention of inheritance and such is, I think, a red herring. (Not sure I fully agree with the closure, but I don't disagree enough to unclose it myself, esp. in light of the parent.b/child.b thing. :-) ) Commented Jul 9, 2019 at 11:00
  • 1
    @T.J.Crowder I know, but the OP has a lack of knowledge on what is really happening when s/he only assigns an object to a variable. Commented Jul 9, 2019 at 11:02
  • 1
    @Ele - Yes, wholeheartedly agree. Commented Jul 9, 2019 at 11:03

1 Answer 1

0

When you do var child = parent both child and parent refer to the same object instance in memory. If you want to copy the property of parent to the child you need to create a new object with the same keys as the parent object. You can use spread ... or object.assign for this

var parent = {
  a: 5,
  b: 6
}

var child = {...parent};
var child1 = Object.assign({}, parent);

console.log(child.b); // 6
console.log(child1.b); // 6

//now if I change the value of b
parent.b = 7

console.log(parent.b); //7
console.log(child.b); //6
console.log(child1.b); //6

For deep cloning, we need to use other alternatives because Object.assign() and ... copies property values. If the source value is a reference to an object, it only copies that reference value.

Sign up to request clarification or add additional context in comments.

4 Comments

This is not a totally cloning approach, this is just spreading the first level of the object.
@T.J.Crowder I have removed that line. I was not talking in those terms. Although yes it sounds confusing if you think it like that.
var child = {...parent}; SyntaxError: Unexpected token ... at createScript (vm.js:56:10) at Object.runInNewContext (vm.js:93:10)
@user3647491 The editor is giving you this error, It Might be the case that editor doesn't support ES6 syntaxes although it is completely a valid syntax. You can use Object.assign() instead of ... if it helps.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.