Question

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!

Was it helpful?

Solution

The constructor is used to create a different state for each new object. You want a different state for each User object, but you want methods like saveScore to be shared among the User objects. Placing the saveScore method in the prototype is one way to share the method between objects.

An aside, one should not override the prototype: User.prototype = {...}, one should add to the prototype: User.prototype.saveScore = function(...){...}.

Licensed under: CC-BY-SA with attribution
scroll top