ES6类中的构造函数与原型中的构造函数之间的区别?

ES6类中的构造函数与原型中的构造函数之间的区别?

问题描述:

ES6类和函数原型都具有构造函数,但是我想知道它们是否相同吗?让我给出更多的解释。

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

因此,我创建了一个Cat函数,例如:

So, I create a Cat function, for instance:

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

猫有以下原型:

如果我键入smth,则此构造函数可能会丢失。例如 Cat.prototype = {}; ,但 new Cat(’Name’); 将继续工作。
Ang在ES6中具有以下语法:

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;
    }
}

该类还具有构造函数,它看起来像一个简单的函数。由于类只是原型继承的语法语法,所以Dog类中的构造函数是否与Cat函数中的构造函数相同,或者这些是不同的概念?

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?


由于类只是原型继承的语法糖,Dog类中的构造函数是否与Cat函数中的构造函数相同?

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.

尽管有一些区别,例如 Dog.prototype 是不可写的, Dog 只能用 new $ c $来调用c>。

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