Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,958 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.