Question

So I'm experimenting with Object.create(), Ecmascript 5!

I need to understand something and therefore I see no better place than this.

Question is why is Family #2 changing the Family #1 object?!

Code

window.onload = function() {
     init();
}

function Family(surName) {
  this.surName = surName;
  this.meowMachine = 0;
  this.NameHistory = new Array();
  this.NameHistory[0] = surName;
}

function MakeFamily(familyToInherit, NewSurName, xMeows) {
  var newFam = Object.create(familyToInherit);
  newFam.surName = NewSurName;
  newFam.meowMachine += xMeows;
  newFam.NameHistory[0] = NewSurName;
  return newFam;
}

Family.prototype.myNameIs = function () {
  console.log('Family surname is: ' + this.surName);
}

Family.prototype.myHistoryIs = function() {

   for(var i = 0; i < this.NameHistory.length; i++)
   {
       console.log(this.NameHistory[i]);
   }    
} 

Family.prototype.XamountOfCats= function () {
  console.log('Familjen:' + this.surName + 
      ' Has a total number of cats: ' + this.meowMachine);
}

Family.prototype.ChangeSureName = function(surName) {
  this.NameHistory.push(surName);
  this.surName = surName;
}


function init() {
  //Instantiate Family #1 based on family base object
  var myFam1 = new Family("1# Family the:  Smiths");
  //Instantiate Family #2 based on Family #1 object
  var myFam2 = MakeFamily(myFam1,"2# Family the: Johnsons",2)
  //change the surName of Family #2
  myFam2.ChangeSureName("2# Family the: Simpsons");
  //Instantiate Family  #3 based on family base object
  var myFam3 = new Family("3# Family the: Akbars");
  console.log("------- Family #1 History -------");
  myFam1.myHistoryIs();
  console.log("------- Family #2 History -------");
  myFam2.myHistoryIs();
  console.log("------- Family #3 History -------");
  myFam3.myHistoryIs();
}

Console --> OUTPUT

------- Family #1 History ------- 
2# Family the: Johnsons 
2# Family the: Simpsons 
------- Family #2 History ------- 
2# Family the: Johnsons 
2# Family the: Simpsons 
------- Family #3 History ------- 
3# Family the: Akbars 

The way I want it to behave

    ------- Family #1 History ------- 
    1# Family the:  Smiths
    ------- Family #2 History ------- 
    2# Family the: Johnsons 
    2# Family the: Simpsons 
    ------- Family #3 History ------- 
    3# Family the: Akbars 
Was it helpful?

Solution

In MakeFamily, you must use

newFam.NameHistory = [NewSurName];

instead of

newFam.NameHistory[0] = NewSurName;

If not, you are modifying familyToInherit's NameHistory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top