首先先简单的聊下ES5和ES6中的继承函数
function parent(a,b){ this a = a; this b = b; } function child(c){ this c = c };
经过子集去继承父级:this
parent.call(child,1,2)
而去看call的底层方法可知,继承的过程是经过prototype属性es5
child.prototype = new parent(1,2);
又此可知,ES5继承的实质是先建立了子类元素child的的实例对象,而后再把父类元素parent的原型对象中的属性赋值给子类元素child的实例对象里面,从而实现继承spa
在传统JS中,生成对象是经过建立构造函数,而后定义生成对象prototype
function parent(a,b){ this.a = a; this.b = b; }
而后经过prototype增长对应所需方法或属性code
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实例化调用父类blog
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实现继承原型