简体   繁体   English

ES6类语法不为我们提供“经典”继承吗?

[英]Doesn't ES6 Class Syntax provide us with “classical” inheritance?

I understand that in case of prototypal inheritance, the objects are linked together through a prototype chain. 我了解在原型继承的情况下,对象通过原型链链接在一起。 The inheritance is a "REFERENCE" to some other live object (instantiation). 继承是对其他一些活动对象(实例化)的“引用”。

Where as in case of class-based inheritance, classes (templates) are made to inculcate inheritance. 与基于类的继承一样,通过类(模板)来灌输继承。 Any sub-class instantiation "POSSESSES" an instance of a parent object. 任何子类实例“拥有”父对象的实例。

But how does Javascript not implement "classical" inheritance with the ES6 syntax? 但是,Javascript如何不使用ES6语法实现“经典”继承呢? With the ES6 class syntax, what you're doing is essentially creating templates. 使用ES6类语法,您要做的实际上是创建模板。 And upon the instantiation of an object, a separate live instance of the parent is made every time. 并且在实例化对象时,每次都会创建一个单独的父实例。 Isn't this classical inheritance? 这不是古典继承吗?

No, ES6 class syntax does not implement classical inheritance. 不可以,ES6 class语法不能实现经典继承。 The methods of the class are still placed on a .prototype object that is linked to the instances through prototypical inheritance. 该类的方法仍放置在.prototype对象上,该对象通过原型继承链接到实例。

There is no "templating" going on either. 两者都没有“模板”。 Attributes are not declared beforehand, the shape of instances is not fixed. 事先不声明属性,实例的形状不固定。 They are just plain objects all along, and their properties get created in the constructor. 它们一直都是普通对象,它们的属性在构造函数中创建。

Yes, class is intended to behave like classes in other languages, thus it looks like "classical inheritance". 是的, class作用类似于其他语言的类,因此它看起来像“经典继承”。 Under the hood it is still prototypal inheritance though. 虽然它仍然是原型继承。

class Animal {}
class Human {}

const me = new Human;

Object.setPrototypeOf(me, Animal.prototype);
console.log(me instanceof Animal); // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM