I'm new to JavaScript, ing from a Python background. I'm currently trying to understand the value of working directly with prototypes rather than classes.
Class Approach
For example, below we have a class for Dog
// Class approach
class Dog1 {
genus = "canis";
vertebrate = true;
constructor(name, breed) {
this.name = name;
this.breed = breed;
}
bark() {
console.log("Bark!")
}
}
Prototype Approach
While the equivalent prototype version would be (I believe)
// Prototype approach
function Dog2(name, breed) {
this.name = name;
this.breed = breed;
}
Dog2.prototype.bark = function() {
console.log("Bark!")
}
Dog2.prototype.genus = "canis"
Dog2.prototype.vertebrate = true
In general, I'm really struggling to see the value of the prototype method.
- Adding the method and "class" attribute occurs outside the constructor definition, which seems to inherently makes the code less reusable.
- This may be because I am ing from Python, but the class approach just seems inherently cleaner and more intuitive.
- For example, why do we have to add
bark
andgenus
toDog2.prototype
rather than toDog2
directly? I assume it is becauseDog2
is ultimately a function which is not permitted to have attributes, but which does have a prototype, so we just attachbark
andgenus
to that? But then how can we be assured that the prototype can store attributes?
- For example, why do we have to add
I know that classes are just syntactic sugar so I can use them, but I want to make sure I'm understanding everything correctly.
.prototype
vs .__proto__
I'm also a little confused as to why the prototype
attribute of an object doesn't actually point to its prototype, and what the difference is between .prototype
and .__proto__
. For example, this article has the below diagram for the line function MyConstructor() {}
, where the prototype chain(s) are in green:
Is the idea that MyConstructor
itself is a function, and so its actual prototype .__proto__
must be what it "subclasses" from, inheriting all function-related functionality, but that it is also a constructor, and so we must define the type of object that it actually constructs (i.e. the class that it is the constructor for), which is what its .prototype
object is? So MyConstructor.prototype
is the "class", and MyConstructor
is the mold for that class that is used to create new instances?
Any advice is greatly appreciated!