ES6和ES5中的继承关系梳理

ES5中的继承

ES5中可以通过原型链的方式实现继承。实现方式如下

function Parent() {}
function Child() {}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

此时,Child继承了Parent。在这个关系中,可以看到Child的原型指向了Parent的实例,Child的构造器指向了自己的构造函数。除此之外它们之间还有什么关系呢?在ES5中,还有一个__proto__属性,每一个__proto__属性都指向对应的prototype

const child = new Child();
console.log(child.__proto__ === Child.prototype); // true
console.log(Child.prototype.__proto__ === Parent.prototype); // true

关于原型和原型链之间的关系,之前的文章JS中原型与原型链的关系有所介绍。

在图中可以清晰地看到上述两行代码的执行结果为true

ES6中的继承

ES6中有了类的概念,使用extends关键字实现继承。

再次执行上述的代码

class Parent {}
class Child extends Parent {}

const child = new Child();
console.log(child.__proto__ === Child.prototype); // true
console.log(Child.prototype.__proto__ === Parent.prototype); // true

发现其执行结果仍然为true。针对ES6,可以画出它们的继承关系如下

总结

js之间的继承关系单纯的靠文字去理解还是很容易混淆的。但是如果画出图形来看就一目了然了。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注