最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

constructor - Classes vs prototypes in JavaScript - Stack Overflow

programmeradmin6浏览0评论

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.

  1. Adding the method and "class" attribute occurs outside the constructor definition, which seems to inherently makes the code less reusable.
  2. This may be because I am ing from Python, but the class approach just seems inherently cleaner and more intuitive.
    1. For example, why do we have to add bark and genus to Dog2.prototype rather than to Dog2 directly? I assume it is because Dog2 is ultimately a function which is not permitted to have attributes, but which does have a prototype, so we just attach bark and genus to that? But then how can we be assured that the prototype can store attributes?

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!

发布评论

评论列表(0)

  1. 暂无评论