typescript学习(6)---定义类

一、类

之前在typescript(3)中定义的类不是合法的ts类,下面进行修改:

class Human {  
  static totalPeople = 0;  
  _name: string;
  constructor(name) {  
    this._name = name;  
    Human.totalPeople += 1;  
  }  
  get name() {  
    return this._name;  
  }  
  set name(val) {  
    this._name = val;  
  }  
  talk() {  
    return `Hi, I'm ${this.name}!`;  
  }  
}  

与之前的区别只在于_name属性的声明是强类型的,下面是使用方法:

let human = new Human('foo');
console.log(human._name);

注意:ts中构造函数是由constructor()函数指定的。

二、抽象类与继承

基类:

abstract class Duck{
    flyBehavior: FlyBehavior;
    quackBehavior:QuackBehavior;
    constructor(){
        
    }

    abstract diaplay():void;
   
    performFly():void{
        this.flyBehavior.fly();
    }

    performQuack():void{
        this.quackBehavior.quack();
    }

    swim():void{
        console.log("All ducks float, even decoys!");
    }

    setFlyBehavior(fb:FlyBehavior){
        this.flyBehavior = fb;
    }

}

继承类:

class MallardDuck extends Duck{
    constructor(){
        super();
        this.quackBehavior = new Quack();
        this.flyBehavior = new FlyWithWings();
    }

    diaplay():void{
        console.log("I'm a real Mallard duck");
    }
}

没有super()函数会报错。

不能把构造函数写成MallardDuck(){},这样会被当成普通函数,需要调用才能执行而不是new一个实例的时候就执行构造。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值