最近想在重新学下 ES6, 所以就把自己学到的, 记录下加强下自己的理解
首先先简单的聊下 ES5 和 ES6 中的继承
1. 在 es5 中的继承:
- function parent(a,b){
- this a = a;
- this b = b;
- }
- function child(c){
- this c = c
- };
通过子集去继承父级:
parent.call(child,1,2)
而去看 call 的底层方法可知, 继承的过程是通过 prototype 属性
child.prototype = new parent(1,2);
又此可知, ES5 继承的实质是先创建了子类元素 child 的的实例对象, 然后再把父类元素 parent 的原型对象中的属性赋值给子类元素 child 的实例对象里面, 从而实现继承
2.ES6 中的继承
在传统 JS 中, 生成对象是通过创建构造函数, 然后定义生成对象
- function parent(a,b){
- this.a = a;
- this.b = b;
- }
然后通过 prototype 增加对应所需方法或属性
- parent.prototype.methods = function(){
- return 'this is test methods';
- }
- parent.prototype.attr = 'this is test attr';
而 ES6 中引入了类的概念, 也就是 class. 通过关键词 class 去定义对象.
class 是个关键词, 语言糖, 这样能更清晰的读懂所创建的对象,
通过属性 constructor 来接收控制方法传入的参数, 如果不写这个属性, 默认是没有参数的
- class parent{
- curstructor(a,b){
- this.a = a;
- this.b = b;
- }
- }
ES6 中的继承是基于 class 类之间继承的. 通过关键词 extends 实现.
通过 super 实例化调用父类
- class parent{
- constructor(a,b){
- this.a = a;
- this.b = b;
- }
- parentMethods(){
- return this.a + this.b
- }
- }
- class child extends parent{
- constructor(a,b,c){
- super(a,b);
- this.c = c;
- }
- childMethods(){
- return this.c + ',' + super.parentMethods()
- }
- }
- const point = new child(1,2,3);
- alert(point.childMethods());
上面的代码, 是一套简单的 ES6 父子类继承.
相信已经看出来了, 虽明显的区别就是在于 ES6 中, 激活父组件的是 super 方法, 而不是新建实例化, 也就是说, 父类的实例对象是先创建出来的, 调用后, 再去修改子类的构造函数中的 this 完善原型对象.
总结:
ES5 和 ES6 继承最大的区别就是在于:
1.ES5 先创建子类, 在实例化父类并添加到子类 this 中
2.ES6 先创建父类, 在实例化子集中通过调用 super 方法访问父级后, 在通过修改 this 实现继承
来源: https://www.cnblogs.com/wymbk/p/9290232.html