0

In my code snippet I have an object "cat" that I store into two variables "Pelle" and "Kalle". If I change the name of Pelle, it also changes the name of Kalle. I believe it has to do with them being references to cat.

How can I avoid this?

How can I change the value of Pelle without changing the name of Kalle?

Is the problem how I store the values in myFunction, or is the problem when I change the name in modify-function?

var cat = {
    name : "Melvin",
    age: : "9",
    eyeColor : "yellow"
};

var pelle;
var kalle;

myFunction(cat);
modify();
print();

function myFunction(c) {
    pelle = c;   
    kalle = c;
 }

 function modify() {
    pelle.name = "Watts";
 }

 function print() {
    document.getElementById("demo").innerHTML = pelle.name + " " + kalle.name;
 }

Output from print() is Watts Watts.

Desired output is Watts Melvin.

chichi
  • 207
  • 1
  • 4
  • 13
  • `pelle = c; kalle = c;` You are just creating two references to the same object – Freeman Lambda Jun 20 '17 at 16:03
  • 1
    Even if it didn't pass by reference, this example would behave the same way – Mirza Brunjadze Jun 20 '17 at 16:04
  • `pelle`, `kelle`, and `cat` are all the same object, so if you modify it, it will be modified. – JLRishe Jun 20 '17 at 16:04
  • That doesn't give me the solution: How do I get the output to be "Watts Melvin" instead of "Watts Watts"? – chichi Jun 20 '17 at 16:06
  • Ok, so how can I pass it by value, so I get the desired output? – chichi Jun 20 '17 at 16:07
  • You can turn `cat` into a function and then do `kelle/pelle = new Cat()` instead – Nope Jun 20 '17 at 16:08
  • Instead of making Kelle = c, you will need to make Kelle equal to a copy of c. If you are using jquery, there is a good answer here: https://stackoverflow.com/a/5164215/4843530 –  Jun 20 '17 at 16:08
  • If you want to have two unconnected copies of an object that you can modify separately, you need to clone it. I have added a link above to a canonical question about cloning objects. A potentially better approach would be to start off with two separate objects in the first place instead of trying to repurpose one object for multiple uses. – JLRishe Jun 20 '17 at 16:12
  • I believe there are many ways to do it, one of them you can see here: http://jsbin.com/qebomuh/edit?js,console – Mirza Brunjadze Jun 20 '17 at 16:14
  • @JLRishe How do I start with two different objects in the first Place? – chichi Jun 20 '17 at 16:43
  • @chichi `var pelle = { name : "Melvin", age: : "9", eyeColor : "yellow" }; var kalle = { name : "Melvin", age: : "9", eyeColor : "yellow" };` – JLRishe Jun 20 '17 at 18:46

0 Answers0