I am going through a tutorial on OOP in JavaScript (javascriptissexy.com using OOP in JS: What you Need to know).
The instructor is explaining the Constructor/Prototype pattern of object creation. I understand what is going on, but I have a burning question that he doesn't answer!
We begin like this:
function User(name, email) {
this.name = name,
this.email = email,
this.scores = [],
this.etc = etc
}
I get it, and now every var xxx = new User("name", "email") will have an xxx.name, xxx.email, xxx.scores, etc.
But now, we overwrite the prototype:
User.prototype = {
constructor: User;
saveScore: function(...){...},
changeEmail: function(...){...},
showNameAndScore: function(...){...}
}
Now every var xxx = new User(...) will inherit saveScore, changeEmail, and showNameAndScore methods.
I am brand new, but from what I understand, I could have included these functions in the begining:
function User(...) {
this.name = name,
this.saveScore = function(...) {...},
...
}
Instead of editing the prototype right away.
I am waiting for the author to tell me that we include these functions in the prototype because they will be exact carbon copies which the user can't edit, and therefore only need to define them once (in the prototype) rather than on every instance of a User.
Or is he just trying to demonstrate the different flavors of inheritance?
Thank you ahead of time!