ES5和ES6继承和区别

2019-04-24  本文已影响0人  放任自由f0

在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的实例对象里面,从而实现继承

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实现继承

上一篇 下一篇

猜你喜欢

热点阅读