ES6类中的构造函数与原型中的构造函数之间的区别? [英] Difference between constructor in ES6 class and constructor in prototype?

查看:114
本文介绍了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

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

这篇关于ES6类中的构造函数与原型中的构造函数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆