0

So I came across a really strange behavior I cannot seem to find the answer to.

I understand how the keyword this is being used in this.score.push(newscore) in the addScore method; this refers to the specific object that was created. In this case, this is referring to the student object stored in the variable billy.

However, let's say I remove this so the addScore method reads score.push(newscore). Okay, I know this will work as well since score is now referring to the initial input of the new student object creation: [80,90,100]. The scope of score should allow this as well.

What really boggles me is when I call billy.score to view his scores, the new score that has been added by the addScore method is there, saved and stored! How in the world can the new score be stored like so if the score is only referring to the input? Shouldn't the new score not be stored in the score array since it was added to an input and not the property of the object ie. this.score?

Thanks so much in advance for reading and I hope to discuss this with you all!

function Student(name, score){
  this.name = name;
  this.score = score;
  this.addScore = function(newscore){
    this.score.push(newscore) // vs score.push(newscore)
  }
}

var billy = new Student("Billy", [80,90,100]);
matchajune
  • 79
  • 3
  • `this.score` and `score` are both the same array. Arrays are objects, and reference values as such, the assignment `this.score = score;` copies only the reference from the variable to the property but did not create a copy of the array. – Bergi Dec 11 '15 at 10:14
  • @Bergi Thanks Bergi for the answer. I understand that `this.score` and `score` are the same array. However, I never save the input array `score` in a variable. Does the input `score` get instantiated as an instance variable for the particular object in JavaScript? If I delete the whole line of `this.score = score`, the constructor function still works when you `addScore` without pushing the new score into `this.score`. – matchajune Dec 12 '15 at 03:58
  • The parameter `score` *is* a variable. A variable that is available in the constructor scope and that will be preserved through the `.addScore` closure. – Bergi Dec 12 '15 at 10:26

0 Answers0