问题
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