ts中的implements

在js中,一个class只能继承自另一个class,若其他类中的方法与属性也想继承,则很麻烦。而在ts中可以使用implements来实现一些类共有方法属性的提取。

class Car{
    switchRadio(trigger:boolean){
        
    }
}

class cellphone{
    switchRadio(trigger:boolean){
        
    }
}

上述两个类都有一个共同的方法,我们可以使用interface接口把他提取出来,implements实现它。此时car和cellphone两个类中都需要有switchRadio方法,不然会报错。

interface Radio{
    switchRadio(trigger:boolean):void        //注意写法,void表示函数没有返回值
}

class Car implements Radio{
    switchRadio(trigger:boolean){
        
    }
}

class cellphone implements Radio{
    switchRadio(trigger:boolean){
        
    }
}

新加一个Battery interface,使cellphone类接入而car类不接入。

interface Battery{
    checkBatteryStatus():void;
}

interface Radio{
    switchRadio(trigger:boolean):void;       //注意写法,void表示函数没有返回值
}

class Car implements Radio{
    switchRadio(trigger:boolean){
        
    }
}

class cellphone implements Radio,Battery{        //逗号连接
    switchRadio(trigger:boolean){
        
    }

    checkBatteryStatus(){        //内部方法加上checkBatteryStatus,注意:不能少!!!!!

    }
}

interface还可以继承,直接用extends即可

interface Battery{
    checkBatteryStatus():void;
}

interface Radio{
    switchRadio(trigger:boolean):void;       //注意写法,void表示函数没有返回值
}

interface BatterywithRadio extends Radio{
    checkBatteryStatus():void;
}

class Car implements Radio{
    switchRadio(trigger:boolean){
        
    }
}

class cellphone implements BatterywithRadio{        //逗号连接
    switchRadio(trigger:boolean){
        
    }

    checkBatteryStatus(){

    }
}

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值