JS继承实现⽅式也很多,主要分ES5和ES6继承的实现
ES5实现继承主要是基于prototype来实现的,具体有三种⽅法
-
原型链继承:即 B.prototype=new A()
function F() { this.f = 'zzz' this.say = () => console.log(' F i say') } F.prototype.talk = () => console.log(' F i talk') var f = new F() function S() { this.s = 'xxx' this.speck = () => console.log('S i speck') } S.prototype = new F() S.prototype.tell = () => console.log('S i tell'); S.prototype.constructor = S var s = new S() console.log(s)
-
借⽤构造函数继承(call或者apply的⽅式继承)
-
组合继承是结合原型链继承和借用构造函数继承
ES6继承
⽤class关键字定义类,⽤extends关键字继承类,⽤super()表示⽗类