admin管理员组文章数量:1336632
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!
本文标签:
constructorClasses vs prototypes in JavaScriptStack Overflow
版权声明:本文标题:constructor - Classes vs prototypes in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:http://www.betaflare.com/web/1742250431a2440653.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论