Difference between constructor in ES6 class and constructor in prototype?

六眼飞鱼酱① 提交于 2019-12-20 04:58:07

问题


Both ES6 class and prototype of function have a contructor, but I'm wondering are they the same? Let me give more explanations.

So, I create a Cat function, for instance:

const Cat = function (name) {
    this.name = name;
};

The Cat has the following prototype: This constructor can be lost if I type smth. like Cat.prototype = {};, but new Cat('Name'); will continue working. Ang we have the following syntax in ES6:

class Dog {
    constructor(name) {
        this.name = name;
    }
}

The class also has constructor and it looks just like a simple function. Since classes are just a syntactic sygar over prototype inheritance, is the constructor function in Dog class is just the same as in Cat function or these are different concepts?


回答1:


Since classes are just a syntactic sugar over prototype inheritance, is the constructor function in Dog class just the same as in Cat function?

Yes, the constructor-prototype relationship still works the same.

There are a few differences though, for example Dog.prototype is not writable and Dog can only be called with new.



来源:https://stackoverflow.com/questions/49803141/difference-between-constructor-in-es6-class-and-constructor-in-prototype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!