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
Shazad Kazi
10,758 PointsPrototypes and Constructors
Can someone please breakdown the use of prototypes. I understand the function is outside. I'm still having trouble understanding where and when to use it and constructors. If you could provide examples when to and when not to. I would be eternally grateful.
3 Answers
Thomas Nilsen
14,957 PointsThe prototype property is created internally once you declare a function like this:
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
Let's add a function to our prototype:
Person.prototype.sayHello = function() {
console.log('Hello ' + this.firstname + ' ' + this.lastname);
}
Now, Everything you put on the Prototype can be accessed by any instances created using new Person, which means we can do something like this:
var p1 = new Person('John', 'Doe');
var p2 = new Person('Jane', 'Doe');
p1.sayHello();
Every instance created from Person will have a proto property which will point to the Person.prototype. This is what's known as Prototypal inheritance.
So to sum it up;
An instance created from Person will have a proto property pointing to Person.prototype.
Person is a Function Object and it will have a proto property that points to the Function.prototype.
The Function.prototype will again have a proto pointing to the Object.prototype.
The Object.prototype is the absolute top level.
Thomas Nilsen
14,957 PointsWhat I mean by 'absolute top level', is when you follow the prototype chain to the top, it stops at the Object.prototype.
The Object.prototype's proto is null. Look at the link I included in my answer.
Shazad Kazi
10,758 PointsThanks, Appreciate the help and I respect the time you put into the post. I still find I may need to read a few more articles to get my head around it.
Thomas Nilsen
14,957 PointsNo problem - This is a really confusing topic.
Shazad Kazi
10,758 PointsShazad Kazi
10,758 PointsFirst of all, thank you for answer.
Just curious as to which circumstances would you use this instead of other javascript methods (not including constructors). It is starting to make sense but as there are so many methods to choose from it does get confusing.
What do you mean by absolute top level