JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一。那么如何在JS中实现继承呢?让我们拭目以待。
当然JavaScript最常用的两种方式便是ES5的写法和Es6的写法,接下来请见详情代码:
xxxxxxxxxx201 function Human(name){2 this.name = name3 }4 Human.prototype.run = function(){5 console.log("我叫"+this.name+",我在跑")6 return undefined7 }8 function Man(name){9 //将Man的name覆盖掉父类的name10 Human.call(this, name)11 this.gender = '男'12 }1314 var f = function(){}15 f.prototype = Human.prototype16 Man.prototype = new f() //IE的话是不能够操作__proto__ 没有实现ECMAScript标准的! 只能通过new 操作__proto__的!1718 Man.prototype.fight = function(){19 console.log('糊你熊脸')20 }ES5中的话,通过prototype还是比较好理解的! 通过原型链使之对应的子类有其父类的共有属性和方法 还有就是第14句和第16句的方法因为IE浏览器没有实现ECMASCRIPT标准 因此不能直接使用__proto__ 因此使用new来操作__proto__使之父子类之间的关联!
xxxxxxxxxx181 class Human{2 constructor(name){3 this.name = name4 }5 run(){6 console.log("我叫"+this.name+",我在跑")7 return undefined8 }9 }10 class Man extends Human{11 constructor(name){12 super(name)13 this.gender = '男'14 }15 fight(){16 console.log('糊你熊脸')17 }18 }ES6的话其中的实现细节有点类似于 Java,也是通过extends关键字达到继承与被继承的父与子类之间的关系 还有对应的构造器来对参数列表进行传参和复用操作!
关于JS继承之间比较经典的两种实现方式中,ES5和ES6的实现方式其实还有各有不同的: