JavaScript語言基於函數與原型鏈繼承的方式來構建可重用組件。對於OO編程來講會很奇怪,在下一代JavaScript標準(ES6)已經爲咱們提供OO設計方式。而TypeScript已經實現這種方式,無須等待ES6就能夠放心的使用。html
類
class Greeter { greeting: string; // public 屬性 constructor(message: string) { // 類構造函數 this.greeting = message; } greet() { // public 方法 return "Hello, " + this.greeting; } } // 使用new實例一個Greeter對象 var greeter = new Greeter("world");
和其餘語言同樣,咱們能夠在類方法裏面使用 this
來表明當前實例的對象。typescript
繼承
OO編程最基本就是繼承,先來看一個示例:編程
class Animal { name: string; constructor(theName: string) { this.name = theName; } move(meters: number = 0) { alert(this.name + ' moved ' + meters + 'm.'); } } class Snake extends Animal { constructor(name: string) { super(name); } move(meters = 5) { alert('Slithering...'); super.move(meters); } } class Horse extends Animal { constructor(name: string) { super(name); } move(meters = 45) { // 重寫父類方法 alert('Galloping...'); super.move(meters); // 調用父類方法 } } var sam = new Snake('Sammy the Python'); var tom: Animal = new Horse('Tommy the Palomino'); sam.move(); tom.move(34);
案例中和普通類只不過多了一個 extend
來表示類的繼承關係,這和接口不一樣,只容許單一繼承。函數
Private/Public 訪問限制
在TypeScript中默認的訪問限制爲:public,這也就是爲何上面的案例都沒有出現 public 字眼。若是想定義私有方法只須在方法前加:private。post
class Animal { private name: string; constructor(theName: string) { this.name = theName; } say() { alert(this.name); } }
參數屬性
參數屬性是訪問限制另外一種簡單的寫法,好比咱們將上面案例改寫成:this
class Animal { constructor(private name: string) { } say() { alert(this.name); } }
當咱們在構造函數裏聲明一個帶有 private
屬性時,同時會自動將這個屬性初始化成一個類私有屬性。spa
屬性訪問器
在C#裏,能夠對某個屬性的讀和寫(即:public string name { get; set; } )操做時執行語句。一樣,TypeScript也有相似的實現方式。設計
class Employee { private _fullname: string; get fullname(): string { return this._fullname; } set fullname(newName: string) { // 作點其它的 this._fullname = newName; } } var employee = new Employee(); employee.fullname = "asdf"; alert(employee.fullname);
靜態
經過 static
標記某個屬性或方法,這和我其餘語言的使用方法同樣,其可見性都是爲類級訪問。日誌
class Grid { constructor(public scale: number) { } static origin = { x: 0, y: 0 } // 靜態屬性 static show() { // 靜態方法 alert('sho'); } cal(point: { x: number; y: number; }) { var xDist = (point.x - Grid.origin.x); var yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; } } var grid1 = new Grid(1.0); // 1x scale var grid2 = new Grid(5.0); // 5x scale alert(grid1.cal({ x: 10, y: 10 })); alert(grid2.cal({ x: 10, y: 10 }));