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]);