zoukankan      html  css  js  c++  java
  • TS之类与接口

     1.类与接口

    interface Raddio {
      switchRadio(trigger: boolean): void
    }
    
    class Car implements Raddio {
      switchRadio(trigger: boolean) {}
    }
    
    class CellPhone implements Raddio {
      // switchRadio(trigger: boolean) {}
    }

    JS中的类只能通过继承自另外一个类,有时候不同的类之间需要实现一个共同的方法,使用子类继承父类的方法很难完成。此时可以把这写共同的特性提取成接口,使用implements关键字来实现,这样就大大提高了面向对象的灵活性。

    示例:

      两个类,但是都要实现一个相同的方法:

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

    switchRadio方法就是这两个类都要实现的相同的方法。此时如果使用父类的形式来实现。那么需要有个父类让这两个类来继承自这个父类。此时可以使用TS的接口来实现这个功能:
    先定义一个接口,然后使用implements关键字让这个类来实现它:

    interface Raddio {
      switchRadio(trigger: boolean): void
    }
    
    class Car implements Raddio {
      switchRadio(trigger: boolean) {}
    }
    
    class CellPhone implements Raddio {}

    此时如果第二个类没有实现这个方法的话就会出现错误提示:Class 'CellPhone' incorrectly implements interface 'Raddio'.Property 'switchRadio' is missing in type 'CellPhone' but required in type 'Raddio'

     2.接口之间的继承

    注意这里接口的继承不是class的继承。

     例如一个类需要实现两个接口里面的方法,可以使用同时实现两个接口的方法实现:

    interface Radio {
      switchRadio(trigger: boolean): void
    }
    
    interface Battery {
      checkBatteryStatus(): void
    }
    
    class CellPhone implements Radio, Battery {
      switchRadio(trigger: boolean) {}
      checkBatteryStatus() {}
    }

    这样 CellPhone 这个类就实现了两个接口的两个方法,还有一种方法就是使用另一个接口继承自Radio接口,CellPhone类就可以只实现一个接口即可:

    interface Radio {
      switchRadio(trigger: boolean): void
    }
    
    interface RadioWithBattery extends Radio {
      checkBatteryStatus(): void
    }
    
    class CellPhone implements RadioWithBattery {
      switchRadio(trigger: boolean) {}
      checkBatteryStatus() {}
    }

    接口继承 使用方法同类的继承,都是使用extends关键字

  • 相关阅读:
    js post 异步请求
    Android 实现文件上传功能(upload)
    js 金额文本框实现代码
    纯CSS画的基本图形(矩形、圆形、三角形、多边形、爱心、八卦等)
    NBearV2视频教学系列总索引,欢迎多提意见和建议[09/21更新至IoC篇]
    1.2 实体实例化及使用自定义实体[发布时间:9/6]
    NBear视频 4.1 基于NBear.IoC的企业级系统构架[发布时间:9/21]
    2.1 基于NBear.Data的实体持久化[发布时间:9/10]
    NBear案例源码 简易AJAX留言板 [Updated 10/31 Powered by NBear V3.0.0 preview]
    全面解析ASP.NET2.0下的URL重写
  • 原文地址:https://www.cnblogs.com/codexlx/p/14442716.html
Copyright © 2011-2022 走看看