js 实现继承
一、使用原型链
function Animal1(leg){ this.leg=leg; } function Dog1(name){ this.name=name; Animal1.call(this,4) //!!import1 } Dog1.prototype.__proto__=Animal1.prototype //!!import2 这句代码被砍了用以下替代
//var f = function(){ }; f.prototype = Animal1.prototype; Dog1.prototype = new f(); Dog1.prototype.say=function(){ console.log(this.name+this.leg) } const d=new Dog1('12') // 124
二、使用类:Class 可以通过extends
关键字实现继承,让子类继承父类的属性和方法。
class Animal{ constructor(leg){ this.leg=leg } } class Dog extends Animal{ constructor(name){ super(4); this.name=name; } say(){ console.log(`i'm ${this.name}, i have ${this.leg} legs`) } } const d=new Dog('12'); d.say() //i'm 12, i have 4 legs