前言
这篇文章将结合上一篇《理论篇:深入解析js中prototype、__ proto __、constructor》 进行实践,结合下面代码画出它们之间的关系图。
class extends继承
class Parent {}
class Children extends Parent {}
const child = new Children();
分析上面的代码,实例对象child, 构造函数有Children、Parent、Function;原型对象对应分别有Children.prototype、Parent.prototype、Function.prototype、Object.prototype;我们先不考虑function和Object,画出最基础的部分:
任何函数都可以看做是通过Function()构造函数new操作实例化的结果 我们把Function加上,这里要注意一个特殊指向 Function.__ proto__ 指向 Function.prototype
所有的对象都可以看成是Object()构造函数new操作的实例化结果 我们加上Object
Object.create类式继承
使用Object.create类式继承会有什么不一样呢?
function Parent() {}
function Children() {}
Children.prototype = Object.create(Parent.prototype);
const child = new Children();
- Children 构造函数及其实例的 constructor 指向会变成 Parent。
- Parent的静态方法和属性不会自动继承,只会继承 Parent 原型链上的属性和方法。
- Children 构造函数在原型链上不会继承 Parent 构造函数(当然在大多数情况下,我们不关心它而是关心实例的原型链)
下一篇深入解析Object.create的应用与实践详细介绍Object.create,及如何弥补与class extends方式实现继承的差异。
如果文章对你有帮助,请先点赞再收藏哦!