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

Why is it better to attach a method to the objects prototype, rather than on the object itself?

I don't fully understand the use of using the prototype property. What are the benefits? I think I heard something along the lines of its good in terms of memory? But, generally, all I've heard about it, is that its good coding practice. But why?

Thanks

1 Answer

Steven Parker
Steven Parker
231,007 Points

The memory benefit is probably the significant advantage. A method defined directly in the class will be replicated for each instance created, but one defined in the prototype will be shared by all instances.

Another advantage is that if you modify or add a method using the prototype, it becomes available on all existing instances. But any additions or changes made to the class itself only affect new instances and all existing ones will remain as they were.

Thanks, Steven. Great explanation! So, there can only be one prototype? the prototype never gets duplicated with instance of an object?

Thanks

Steven Parker
Steven Parker
231,007 Points

That's right, the instances all share the prototype.