十一、Js继承
ES6
-
采用extends关键词对父类的继承
❗注意:一定要在子类构造器第一行加入super父类构造器的调用
class Parent { constructor(){ this.age = 10 } } class Child extends Parent { constructor(){ super() //若继承则必须加上super -- 否则报错 this.name = 'jaws' } } console.log(new Child().age) //若没有继承extends则视为undefined
原型链
-
将原型指向父类即可
function Parent { this.age = 10 } function Child { this.name = 'jaws' } Child.prototype = new Parent() console.log(new Child().age) //10
借用构造函数
-
利用call方法改变this指向:无法实现共享
function Parent { this.age = 10 } function Child { this.name = 'jaws' Parent.call(this) } console.log(new Child().age) //10
组合式
-
可以实现共享、又可以解决原型链的继承的问题
function Parent { this.age = 10 } function Child { // 2.将this指向父类 Parent.call(this) this.name = 'jaws' } // 1. 将原型链串联起来 Child.prototype = new Parent()