js继承的几种常见方式
I keep asking myself these three questions… What do you have? What do you want? What will you give up?
— Jack Ma
本系列关注前端部分,根据学习路线图达到学习Vue.js的目的
developer路线图developer-roadmap/translations/chinese at master · kamranahmedse/developer-roadmap
本系列笔记的源代码GitHub项目地址:learning-area/front-end-learning at master · YJ2CS/learning-area
快速跳转
目录:前端学习路线-目录
本文由 简悦 SimpRead 转码, 原文地址 zhuanlan.zhihu.com
继承在 js 中占有非常重要的地位,那么在 js 中有很多中继承的方式,不过每一种继承方式都有优缺点。下面就列举几种继承的方式。
实现继承首先需要一个父类,在 js 中实际上是没有其他语言(C++/java等)中标准的类的概念,在 es6 中 class 虽然很像类,但实际上只是 es5 上语法糖而已
1 | function People(name){ |
1. 原型链继承
父类的实例作为子类的原型
1 | function Woman(){ |
优点:
简单易于实现,父类的新增的实例与属性子类都能访问
缺点:
可以在子类中增加实例属性,如果要新增加原型属性和方法需要在 new 父类构造函数的后面
无法实现多继承
创建子类实例时,不能向父类构造函数中传参数
2. 借用构造函数继承(伪造对象、经典继承)
复制父类的实例属性给子类
1 | function Woman(name){ |
优点:
解决了子类构造函数向父类构造函数中传递参数
可以实现多继承(call 或者 apply 多个父类)
缺点:
方法都在构造函数中定义,无法复用
不能继承原型属性 / 方法,只能继承父类的实例属性和方法
3. 实例继承(原型式继承)
1 | function Wonman(name){ |
优点:
不限制调用方式
简单,易实现
缺点:不能多次继承
4. 组合式继承
调用父类构造函数,继承父类的属性,通过将父类实例作为子类原型,实现函数复用
1 | function People(name,age){ |
缺点:
由于调用了两次父类,所以产生了两份实例
优点:
函数可以复用
不存在引用属性问题
可以继承属性和方法,并且可以继承原型的属性和方法
寄生组合继承
通过寄生的方式来修复组合式继承的不足,完美的实现继承
1 | //父类 |
es6 继承
代码量少,易懂
1 | //class 相当于es5中构造函数 |
ES5 继承和 ES6 继承的区别
es5 继承首先是在子类中创建自己的 this 指向,最后将方法添加到 this 中
Child.prototype=new Parent() || Parent.apply(this) || Parent.call(this)
es6 继承是使用关键字先创建父类的实例对象 this,最后在子类 class 中修改 this
结束语:
es6 中很多代码的语法糖,很多方法简单易用。在浏览器兼容的情况下,改变原有方式。
虽然现在很多框架都是 es6,但对于初学者还是建议多看看 es5 中实现的原理。