类-继承 继承可以让子类获得父类(基类)的方法、属性,可以扩充,增加新的方法和属性等 extends class P { constructor(name,age) { this.name = name this.age = age } say () { console.log(this.name) } } class
类-继承
继承可以让子类获得父类(基类)的方法、属性,可以扩充,增加新的方法和属性等
extends
class P { constructor(name,age) { this.name = name this.age = age } say () { console.log(this.name) } } class L extends P { constructor(name,age,sex,hobby) { super(name,age) this.sex = sex this.hobby = hobby } say() { console.log(`${this.name} + ${this.hobby}`) } } let p = new P ("xiaoming",32) p.say() //xiaoming let l = new L("kangkang",23,"man","唱歌") l.say() //kangkang + 唱歌
子类中的方法和父类中重名时会以子类为准。
super()
作用
作为父类构造函数调用
调用后子类可以得到父类的属性和方法(要在开头就调用)(将子类的this放在了父类的构造函数中运行一遍)
作为对象的方式调用
非静态方法中访问super -> 父类原型
在静态方法中访问super ->父类
在调用super时,父类运行中this始终会是子类的this
class L extends P { constructor(name,age,sex,hobby) { super(name,age) this.sex = sex this.hobby = hobby } say() { console.log(`${this.name} + ${this.hobby}`) } }
多态
同一个接口,在不同情况下做不一样的事情(相同接口,不同表现)
class L extends P { constructor(name,age,sex,hobby) { super(name,age) this.sex = sex this.hobby = hobby } say() { super.say() // 同一函数名不同结果 console.log(`${this.name} + ${this.hobby}`) } }
重载
函数参数不同,进行不同操作
ES5中类继承实现
function P() { this.name = "kangang" this.gender = 2 this.say = function () { console.log("我是父类的哦!") } } P.prototype.test = function() { console.log(`我是原型上的test方法!!!`) } function C() { P.call(this) this.name = "xiaojun" this.age = 21 } var child = new C() child.say() //我是父类的哦! child.test() // child.test is not a function // 上面的解决方法是 C.prototype = new P()