Search code examples
javascriptclassfirefoxbrowserprototype

Understanding (missunderstanding?) prototype based classes in JavaScript



I'm trying to understand how prototype class system works in JS. So far I'm little bit confused about the results I've got after creating and displaying objects (in Firefox).
When I create an object using 'Example 1' I got an object who's prototype has one property (speak function) and who has an instance property 'type'. And this behavior is clear.
But in the second example, using keyword 'new' I got an object with an instance property 'type' and a prototype who has a constructor itself (Rabbit) and defined function 'speak'. And this function 'speak' has non empty 'prototype' property and this relation going further etc. Same with prototype constructor. His constructor has 'prototype' property holding the same content as previous level and etc.
And this behavior seems like an infinite recursion tree. I do not understand if this behavior is normal language "feature"?

// Example 1
let protoRabbit = {
    speak(line) {
    console.log(`The ${this.type} rabbit says '${line}'`);
    }
};
function makeRabbit(type) {
    let rabbit = Object.create(protoRabbit);
    rabbit.type = type;
    return rabbit;
}
// Example 2
function Rabbit(type) {
    this.type = type;
}
Rabbit.prototype.speak = function(line) {
    console.log(`The ${this.type} rabbit says '${line}'`);
};
let weirdRabbit = new Rabbit("weird");
console.log(weirdRabbit);

Solution

  • It is not actually 'infinite' even if it seems like it. The prototype's constructor of the (Rabbit) object refers back to itself, so as you go deeper, you are just opening the same (Rabbit) object over and over again.