1. 程式人生 > 實用技巧 >typeScript學習筆記-03

typeScript學習筆記-03

// 1類的定義
class Person{
    name:string;
    age:number;
    constructor(name:string,age:number){
        this.name=name;
        this.age=age;
    }

    print(){
        return this.name+":"+this.age
    }
}

var p=new Person('zhangsan',20)

console.log(p.print())


// 類的繼承

// class Student extends Person{
// cardnumber:string; // school:string; // dohmoework(){ // return this.name+"今年"+this.age+"歲,就讀於"+this.school+"學號"+this.cardnumber // } // } // let stu=new Student('王笑',20) // stu.cardnumber="10" // stu.school="大學" // console.log(stu.dohmoework()) class Student extends Person{ cardnumber:string; school:string; constructor(cardnumber:string,school:string){ super(
'馬大哈',10); this.cardnumber=cardnumber; this.school=school; } print(){ return this.name+"今年"+this.age+"歲,就讀於"+this.school+"學號"+this.cardnumber } } let stu=new Student('10','大學'); console.log(stu.print()) //子類自己身上有的方法不會取父類身上找 馬大哈今年10歲,就讀於大學學號10 // 介面的繼承 interface Printer1{ getmsg1(); } interface ColorPrinter extends Printer1{ printing1() } class Hpprinter implements ColorPrinter{ printing1(){ console.log(
'列印成功') } getmsg1(){ console.log('HP1020490') } } var hp=new Hpprinter() hp.getmsg1() hp.printing1() // 訪問修飾符 // public(公共的) private(私有的) protected(受保護的) class Person1{ public name:string; private age:number; protected email:string constructor(name:string,age:number,email:string){ this.name=name; this.age=age; this.email=email; } print(){ return this.name+":"+this.age } } var P1=new Person1('zhangsan',15,'[email protected]'); console.log(P1.name); // console.log(P1.age) 因為age設定了 private私有屬性所以訪問會報錯 // console.log(P1.email) 因為email設定了受保護的屬性,所以訪問也會報錯 只有它的子類可以訪問 class mStudent extends Person1{ show(){ console.log(this.email) //是Person1的子類所以可以訪問email } } // javascript的靜態屬性和靜態方法 function People(){ // 例項屬性 this.name="zhangsan" // 例項方法 this.print=function(){ } } People.age=19 //靜態屬性 // 靜態方法 People.print=function(){} People.print()//呼叫靜態方法 console.log(People.age) var p2=new People() p2.print()//呼叫例項方法 class Person2{ // 例項屬性 public name:string; static age:number; protected email:string constructor(name:string,age:number,email:string){ this.name=name; this.email=email; } print(){ return this.name+":" } // 靜態方法 static show(){ } } // 呼叫靜態方法 Person2.show(); var p3=new Person2('wangxiao',11,'@qq') console.log(p3.print()) // 多型 同一個父類下邊不同的子類可以有不同的實現 class Animal{ eat(){ console.log('animal is eat') } } class Cat extends Animal{ eat(){ console.log('貓吃魚') } } class Dog extends Animal{ eat(){ console.log('狗吃肉') } } var cat1=new Cat() cat1.eat(); // 抽象類、抽象方法 // 抽象類是提供其他類繼承的基類(父類),不能直接被例項 // 抽象方法只能包含在抽象類中,抽象類中可以包含抽象方法和非抽象方法 // 子類繼承抽象類,實現抽象方法 // abstract 抽象類關鍵字 abstract class Animal1{ abstract eat(); run(){ console.log("run in run") } } class Cat1 extends Animal1{ eat(){ console.log('貓吃魚1') } } class Dog1 extends Animal1{ eat(){ console.log('狗吃肉1') } } let c1=new Cat1(); c1.eat(); let d1=new Dog() d1.eat()