ts 中 interface 與 class 的區別


interface: 接口只聲明成員方法,不做實現。
class: 類聲明並實現方法。
也就是說:interface只是定義了這個接口會有什么,但是沒有告訴你具體是什么。
例如:
interface Point {
  lng: number;
  lat: number;
  sayPosition(): void;
}
Point interface 里面包含數值類型的經緯度和一個sayPosition函數,但是具體內容沒有定義,需要你自己在子類中實現。

而class則是完整的實現:
class Point {
  constructor(lng, lat) {
    this.lng = lng;
    this.lat = lat;
  }
  sayPosition() {
    console.log("point:", this.lng, this.lat);
  }
}

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM