0

I am trying to initialize a new object's values with an already existing values, but I don't want it to be pointing to the same object in memory. I want it to be a new object by itself. That is, if I change data members of one object, the other object's data members should remain unchanged. I tried the below code, but it makes the new object to point to the same object in memory.

<script type="text/javascript">
    var ob1 = {name : "hello"};
    document.write(ob1.name + ",");
    var ob2 = ob1;
    ob1.name = "world";
    document.write(ob1.name + ",");
    document.write(ob2.name);
</script>

This code snippet prints hello,world,world. I want the resulting code to be able to print hello,world,hello. So, can anybody please help me in resolving this?

  • Just create a new object: `var ob2 = {};` instead of referencing `ob1`. – Bergi Feb 07 '15 at 16:30
  • Your code is doing exactly what it's supposed to. If you don't want to reference `obj1`, then don't equate it to another variable. – Waxi Feb 07 '15 at 16:31

0 Answers0