随着快速的发展,如今的继承方式也和以前有了很大的区别,下面我为大家罗列一下常见的四种寄生方式。
第一种:原型继承方式,这种继承发誓比较古老,缺陷也很大,甚至都算不上是继承。
function parent(){
this.x = 10
}
function child(){
}
child.prototype = new parent
这种继承发誓简单而粗暴,直接利用子类和父类的关系吧父类原型上公有的,以及私有的全部继承,单根本原理还是利用的原型链查找根本算不上继承,而且还会造成constructoer的丢失问题;
第二种继承方式:call继承,这个就更加简单了,直接把父级当做普通函数执行,用call改变this指向,让其this变为子级的实例,这种继承方式,只是把父级私有的拷贝了一份给子级的实例;
function parent(){
this.x = 10
}
function child(){
parent.call(this)
}
new child
第三种继承方式:寄生组合继承方式,这种是比较完善的一种es5的继承发誓,相对比较完整了许多;
function parent(){
this.x = 10
}
function child(){
parent.call(this)
}
child.prototype = Object.careat(parent.prototype)
child.prototype.constructor = child;
new child
第四种:以上三种继承方式,实际上算是已经被淘汰的继承方式,在ES6强大而有方便的代码勉强,以上三种早已成为历史:
class parent{
constructor(){
this.x = 10
}
}
class child extends parent(){
constructor(){
super()
}
}
虽然用着方便 但是值得注意的是新增加的这两个词: extends 和 super
尤其是super这个词,如果在设有constructor的情况下,不加super便会报错;