ES5继承
es5的继承方式有很多种,原型链继承、组合式继承、寄生组合继承,相比来说寄生组合式继承集
组合式继承和寄生式继承的优点于一身,是ES5中,基于类型继承的最有效方式。
寄生组合式继承
function inserit(son, father) {
var obj = Object.create(father.prototype);//创建父类原型的副本
son.prototype = obj;//将该副本的constructor属性指向子类
obj.constructor = son//将子类的原型属性指向副本
}
//父类
function Father(name,colors) {
//父类实例属性
this.name = name;
this.colors = colors;
}
//父类原型方法
Father.prototype.sayName = function () {
return this.colors;
}
//子类
function Child(job,name,color) {
Father.call(this, name,color);
this.job = job;
}
//寄生式继承:将父类原型的副本强制赋值给子类原型,实现继承父类的原型方法。
inserit(Child, Father);
Child.prototype.sayjob = function () {
return this.job;
}
var instance= new Child("Clown","CXK",["jump","sing"]);
console.log(instance.sayjob(),instance.sayName()) //Clown,["jump","sing"]
ES6继承
es6的继承主要是通过class、extends关键字来实现的
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); //在子类的 constructor 中必须先调用 super 才能引用 this
this.c = c;
}
childMethods(){
return this.c + ',' + super.parentMethods()
}
}
const point = new child(1,2,3);
console.log(point.childMethods()); //3,3
es6引入了class(类)这个概念,其实就是一个语法糖,大部分功能es5也可以实现
constructor(构造方法)
class的默认方法,new生成实例的时候会自动调用(类必须用new调用),一个类必须有constructor方法,如果没有显式定义,js引擎会给它自动添加一个空constructor方法,一般 constructor 方法返回实例对象 this ,但是也可以指定 constructor 方法返回一个全新的对象
super
子类必须在constructor方法中调用super
方法,否则新建实例时会报错。这是因为子类自己的this
对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super
方法,子类就得不到this
对象。
在子类的 constructor 中必须先调用 super 才能引用 this,这是因为子类实例的构建,基于父类实例,只有super
方法才能调用父类实例。
上述示例代码中 第一个super是作为函数,只能存在于constructor中,那方法中的super呢,这就是它的第二种用法,作为对象,指向父类的原型对象,所以可以调用parentMethods方法,注意由于super
指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过super
调用的。不能super.a
区别
ES5先创建子类,在实例化父类并添加到子类this中
ES6先创建父类,在实例化子集中通过调用super方法访问父级后,在通过修改this实现继承