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

William Hurst
William Hurst
25,074 Points

Help understanding JS prototypes

I am comparing the JS class to the traditional JS class and I do not fully understand the process.

Example:

constructor

function Animal(name, weight) {
    this.name = name;
    this.weight = weight;
}

adding methods to the prototype make the methods available to the class

Animal.prototype.eat = function(){
    return `${this.name} is eating`;
}
Animal.prototype.sleep = function(){
    return `${this.name} is going to sleep`;
}
Animal.prototype.wakeUp = function(){
    return `${this.name} is waking up`;
}

allow the Animal constructor to be called on Gorilla

passing this to make sure the call is made from Gorilla

function Gorilla(name, weight) {
    Animal.call(this, name, weight);
}

set the Gorilla's function's prototype as a new object created from the Animal's prototype

Gorilla.prototype = Object.create(Animal.prototype);

after setting the Gorilla's function's prototype from Animal's prototype (overriding Gorialla's prototype object) - why do you have to do the below line - setting the constructor of Gorilla explicitly?

the code has already made Gorilla inherit "characteristics" from Animal and set the Gorilla's prototype as a new object created from the Animal's prototype which means overriding Gorilla's prototype object

this also leads onto what is the prototype.constructor's purpose and why does it need to be set from 'Gorilla.prototype = Object.create(Animal.prototype);'

Gorilla.prototype.constructor = Gorilla;

I am struggling to wrap my head around this, please provide a a solid explanation if you can.

Thanks.