js继承一般分为3种办法,一种是es5基于原型的继承以及es5的call( ),一种是es6基于类继承
// 使用JavaScript继承机制,实现两个类之间的继承。
// 父类:人,属性:年龄、身高、性别。方法:行走、行走、睡觉。// 子类:学生,属性:年级、学分。方法:上学、放学、休学。// 目标,创建子类学生的实例,调用行走、吃饭、睡觉、上学、放学、休学6个方法。【基于原型继承】
//es5实现继承[基于原型继承] function Person(age,height,sex){ this.name=name; this.age=age; this.height=height; this.sex=sex; this.go=function(){ console.log("行走") }; this.eat=function(){ console.log("行走") }; this.sleep=function(){ console.log("睡觉") }; } function Student(nj,sc){ this.nj=nj; this.sc=sc; this.goSchool=function(){ console.log("上学") } this.bybySchool=function(){ console.log("放学") } this.overSchool=function(){ console.log("休学") } } Student.prototype=new Person(); var stu=new Student(2,30); stu.go(); stu.sleep(); stu.goSchool(); stu.bybySchool(); stu.overSchool();
【基于类继承】
//es6实现继承[基于类继承] class Person{ constructor(age,height,sex){ this.age=age; this.height=height; this.sex=sex; } go(){ console.log("行走") }; eat(){ console.log("行走") }; sleep(){ console.log("睡觉") }; } class Student extends Person{ constructor(nj,sc){ super() this.nj=nj; this.sc=sc; } goSchool(){ console.log("上学") } bybySchool(){ console.log("放学") } overSchool(){ console.log("休学") } } var stu=new Student(2,30); stu.go(); stu.sleep(); stu.goSchool(); stu.bybySchool(); stu.overSchool();