I joined this meetup every week discussing about the book effective javascript: 68 ways.
In Item 36: Store Instance State Only on Instance Objects, we created the following example to explain it.
function User() {}
User.prototype = {
hobbies: [], // should be instance state!
addHobby: function (x) {
this.hobbies.push(x);
}
};
We instantiate the following users.
boy = new User();
// User {hobbies: Array[0], addHobby: function}
girl = new User();
// User {hobbies: Array[0], addHobby: function}
boy.addHobby("swimming");
girl.addHobby("running");
// undefined
boy.hobbies
// ["swimming", "running"]
girl.hobbies
// ["swimming", "running"]
As you can see, the addHobby function affects hobbies at the prototype level.
Now if I change the entire code to
function User() {}
User.prototype = {
hobbies: [], // should be instance state!
addHobby: function (x) {
newArr = new Array(x);
this.hobbies = this.hobbies.concat(newArr);
}
};
boy = new User();
girl = new User();
boy.addHobby("swimming");
girl.addHobby("running");
boy.hobbies
//["swimming"]
girl.hobbies
//["running"]
We know the reason is because of the assignment. We are looking for a full explanation why this.hobbies = this.hobbies.concat(newArr);
assigns to the instance level and not at the prototype level despite in both instances the term this.hobbies
is used.