1、请编码实现动物世界的继承关系:
动物(Animal)具有行为:吃(eat)、睡觉(sleep)
动物包括:兔子(Rabbit),老虎(Tiger)
这些动物吃的行为各不相同(兔子吃草,老虎吃肉);但睡觉的行为是一致的。
请通过继承实现以上需求,并进行测试。
class Animal{
constructor(sleep){
this.sleep = sleep
}
sleep(){
console.log(this.sleep)
}
}
class Rabbit extends Animal{
constructor(sleep,eat){
super(sleep)
this.eat = eat
}
eat1(){
console.log('兔子')
super.sleep()
console.log(this.eat)
}
}
class Tiger extends Animal{
constructor(sleep,eat){
super(sleep)
this.eat = eat
}
eat2(){
console.log('老虎')
super.sleep()
console.log(this.eat)
}
}
let animal1 = new Rabbit('趴着睡','吃草')
animal1.eat1()
console.log('--------------------------------')
let animal2 = new Tiger('趴着睡','吃肉')
animal2.eat2()
2、定义一个体育活动类(Sports)作为基类,它有一个进行活动的方法play,足球(Football)和篮球(Bascketball)都是体育活动类的派生类。请编写一个方法howToPlay(Sports sp),该方法要求传递一个Sports类型的参数。该方法的作用是:
(1)当传入的对象类型为Football时,控制台上应打印、足球是用脚踢的!
(2)当传入的对象类型为Bascketball时,控制台上应打印、篮球是用手打的!
// 1.定义父类(基类)Sports
class Sports{
constructor(){}
play(){}
}
class Football extends Sports{
constructor(){
super()
}
play(){
console.log('足球是用脚踢的!')
}
}
class Bascketball extends Sports{
constructor(){
super()
}
play(){
console.log('篮球是用手打的!')
}
}
function howToPlay(sp){
sp.play()
}
// let sport = new Sports()//sport是基类的对象
// 第一种:直接给howToPlay函数传递子类对象
// let foot = new Football()
// howToPlay(foot)
// let basket = new Bascketball()
// howToPlay(basket)
// 第二种:父类的对象执行了子类的类型
// sport = new Football()
// howToPlay(sport)
// sport = new Bascketball()
// howToPlay(sport)
let sport = new Sports()//sport是基类的对象
let foot = new Football()
let flag = (foot instanceof Sports)//子类对象是父类Sports类型----向上转型
console.log('flag=',flag)//flag = true
// let flag = (sp instanceof Football)//父类对象sp不能是子类Football类型---不能向下转型
// console.log('flag=',flag)//flag = false
3、编写一个程序,并满足如下要求:
(1)编写一个Car类,具有:
属性:品牌(mark)
功能:驾驶(drive())
(2)定义Car类的子类SubCar,具有:
属性:价格(price)、速度(speed)
功能:变速(speedChange(newSpeed)),把新速度赋给speed
输出效果如下:
class Car{
constructor(mark){
this.mark = mark
}
drive(){
console.log('本车正在驾驶中。。。。')
}
}
class SubCar extends Car{
constructor(mark,price,speed){
super(mark)
this.price = price
this.speed = speed
}
speedChange(newSpeed){
return this.speed = newSpeed
}
show(){
super.drive()
console.log('品牌:',this.mark)
console.log('价格:',this.price)
console.log('原来的速度',this.speed)
}
}
let car1 = new SubCar('奥迪','23.5万','50')
car1.show()
console.log('改变速度之后',car1.speedChange('78'))
这篇博客探讨了如何使用ES6的类实现动物世界的继承关系,包括动物、兔子和老虎,展示不同动物的吃行为。同时,文章还讲解了如何定义体育活动类如足球和篮球,并创建了一个方法来根据传入的运动类型输出相应的活动方式。此外,还介绍了Car类及其子类SubCar的创建,包括属性和功能的定义与实现。
2345

被折叠的 条评论
为什么被折叠?



