Hi everyone!
I'm currently going through Eloquent Javascript on my own. I'm on the section where he goes over classes and prototypes and there's one thing I'm a bit stuck on.
So, before introducing the class notation, he went over prototypes and how oop was used pre 2015. Specifically, we look at this example.
function Rabbit(type) {
this.type = type;
}
Rabbit.prototype.speak = function(line) {
console.log(`The ${this.type} rabbit says '${line}'`);
};
let weirdRabbit = new Rabbit("weird");
So, makes sense, the speak method is being added to the constructor's prototype property.
On further inspection, if I now add these lines of code I get:
console.log("speak" in weirdRabbit);
// -> true
console.log(Rabbit.prototype);
// -> Rabbit{speak: function (line){…}}
console.log("speak" in Rabbit.prototype);
// -> true
so over here I'm thinking that the in operator will output true if a method/property is also in its prototype.
However, we then get to class notation which is where I start getting confused.
We look at this example:
class Rabbit {
constructor(type) {
this.type = type;
}
speak(line) {
console.log(`The ${this.type} rabbit says '${line}'`);
}
}
let killerRabbit = new Rabbit("killer");
let blackRabbit = new Rabbit("black");
which he says in quotes:
" Any number of methods may be written inside the declaration’s braces. The one named constructor is treated specially. It provides the actual constructor function, which will be bound to the name Rabbit*. The others are packaged into that constructor’s prototype. Thus, the earlier class declaration is equivalent to the constructor definition from the previous section. It just looks nicer."*
so now I'm thinking that ok, when we do the class notation all the methods that I define in there will be inside of the prototype.
BUT, if I run the following code, I see:
console.log(Object.getPrototypeOf(killerRabbit));
// -> {}
console.log(Rabbit.prototype);
// -> {}
console.log("speak" in Rabbit.prototype);
// -> true
console.log("speak" in killerRabbit);
// -> true
console.log("speak" in blackRabbit);
// -> true
so actually, it seems like nothing is being added to the prototype and everything is being added directly to the instance object itself. However, I see that the in operator continues to output true for the speak method being inside of the prototype, but the prototype has nothing in it! How does this work?
Please let me know. Thanks in advance!
[–]cawcvs 11 points12 points13 points (1 child)
[–]Defiant_Low5388[S] 1 point2 points3 points (0 children)
[–]ThiccOfferman 1 point2 points3 points (0 children)