ES6 class 中的构造函数和原型中的构造函数之间的区别?
Difference between constructor in ES6 class and constructor in prototype?
ES6 class和函数原型都有一个contructor
,但我想知道它们是一样的吗?让我再解释一下。
因此,我创建了一个 Cat 函数,例如:
const Cat = function (name) {
this.name = name;
};
猫的原型如下:
这个 constructor
如果我输入 smth 可能会丢失。像 Cat.prototype = {};
,但 new Cat('Name');
将继续工作。
Ang 我们在 ES6 中有以下语法:
class Dog {
constructor(name) {
this.name = name;
}
}
class还有constructor
,看起来就是一个简单的函数。由于 classes 只是原型继承的语法 sygar,Dog class 中的构造函数是否与 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?
是的,构造函数-原型关系仍然有效。
虽然有一些区别,例如 Dog.prototype
不可写,而 Dog
只能用 new
调用。
ES6 class和函数原型都有一个contructor
,但我想知道它们是一样的吗?让我再解释一下。
因此,我创建了一个 Cat 函数,例如:
const Cat = function (name) {
this.name = name;
};
猫的原型如下:
constructor
如果我输入 smth 可能会丢失。像 Cat.prototype = {};
,但 new Cat('Name');
将继续工作。
Ang 我们在 ES6 中有以下语法:
class Dog {
constructor(name) {
this.name = name;
}
}
class还有constructor
,看起来就是一个简单的函数。由于 classes 只是原型继承的语法 sygar,Dog class 中的构造函数是否与 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?
是的,构造函数-原型关系仍然有效。
虽然有一些区别,例如 Dog.prototype
不可写,而 Dog
只能用 new
调用。