Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Methods with Prototypes

Is my assumption about prototypes correct?

My definition: prototypes are essentially creating methods on a constructor function but from outside the constructor function.

Is my definition correct?

Let's say we have a constructor function that creates a new user:

function User(first_name, last_name, email, password, friends, favorites) {
    this.first_name = first_name;
    this.last_name = last_name;
    this.email = email;
    this.password = password;
    this.friends = [];
    this.favorites = [];
}

I want to create a few methods that allow the user to add/delete friends and add/delete favorites:

User.prototype.add_friend = function(friend) {
    this.friends = this.friends.push(friend);
}

User.prototype.delete_friend = function(friend) {
    //this.favorites = this.friends.indexOf(friends).delete;
}

User.prototype.add_favorite = function(favorite) {
    this.favorites = this.favorites.push(favorite);
} 

User.prototype.delete_favorite = function(favorite) {
    //this.favorites = this.favorites.indexOf(favorite).delete;
}

By the way, I am not sure how to delete an array item at a given index... so if you could help me out there that would be great!!! Thanks guys!

1 Answer

Steven Parker
Steven Parker
231,269 Points

The main difference is that a function defined in the constructor will be replicated for each instance of the object. A prototype function will be shared by the instances. If you were going to have a large number of objects the memory usage could become significant.

:point_right: You can remove one or more array item(s) using splice(index, count).

Example:

var dogs = ["Beagle", "Pointer", "Mutt", "Weiner", "Labrador"];
dogs.splice(2, 2);
// dogs will now be ["Beagle", "Pointer", "Labrador"];

Splice will also insert items into the array. Look it up from a good reference like MDN.