1. 程式人生 > >八、面向物件特性

八、面向物件特性

                                               面向物件特性

1、類(class)

//屬性可以使用public、private、protect修飾
class Person{ 
	constructor() {
        console.log("構造方法========");  
    }


    public name;
    public eat() {
        console.log("正在吃==========");
    }
}

var p1 = new Person();
p1.name = "pangzi";
p1.eat();

//類的繼承
class student extends Person{
    code: string;
    //子類的構造方法必須呼叫父類構造方法
    constructor(code:string) {
        super();
        this.code = code;
    }
	
	doWoerk(){
	    //使用super關鍵字呼叫父類方法
		super.eat();
	}
}

var stu = new student("023145");

2、泛型(generic)

class Person{ 

    constructor() {
        console.log("構造方法========");  
    }

    public name;
    public eat() {
        console.log("正在吃==========");
    }
}

var p1 = new Person();
p1.name = "pangzi";
p1.eat();


class Student extends Person{
    code: string;
    //子類的構造方法必須呼叫父類構造方法
    constructor(code:string) {
        super();
        this.code = code;
    }
}

var stu = new Student("023145");


//泛型
var students: Array<Person> = [];
students[0]=new Student("023145"); 

3、介面(interface)

interface IPerson{
    name: string;
    age: number;
}

class Person{
    //使用介面來限制引數型別
    constructor(public config:IPerson) {
        
    }
}

var p1 = new Person({
    name: "pangzi",
    age:18
});
interface Animal{
    eat();
}

class Sheep implements Animal{
    eat() {
        console.log("實現介面的class必須實現這個方法");
    }
}

4、模組(module)

模組:類似java中的 導包。 一個檔案就是一個模組,一個模組內部使用兩個關鍵字export、import。 export:宣告模組對外暴露什麼 import:宣告其他模組對這個模組提供什麼

a.ts:

export var pro;

var pro1;

export  function func() {
    
}

export function func1() {
    
}

export class Clazz {
    
}

class Clazz1 {
    
}

b.ts:

import {pro} from "./a";

console.log(pro);

5、註解(annotation)

註解在類上、方法上、屬性上,宣告載入這個類(方法、屬性)時需要做什麼事情

在這裡插入程式碼片

6、型別定義檔案(*.d.ts)

在TypeScript中使用型別定義檔案,幫助開發者在TypeScript中使用已有的JS工具包,比如JQuery。