在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(){

    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐