04_TypeScript类

1、类的定义

//ts定义类和ES6相似,不同的是属性需要修饰符并定义数据类型
class Person{
    public name:string;
    constructor(n:string){
        this.name=n;
    }
    run():void{
        console.log(this.name);
    }
}
var p=new Person('张三');
p.run()

2、类里面的修饰符

  public :公有,在当前类里面、 子类 、类外面都可以访问
  protected保护类型,在当前类里面、子类里面可以访问 ,在类外部没法访问
  private私有,在当前类里面可以访问,子类、类外部都没法访问
  属性如果不加修饰符 默认就是 公有 (public

3、类的继承

//ts类的继承和ES6相似,extends 和 super
class Person{
    name:string;
    constructor(name:string){
        this.name=name;
    }
    run():string{
        return `${this.name}在运动`
    }
}
var p=new Person('张三');
alert(p.run())

class Web extends Person{
    constructor(name:string){
        super(name);  /*初始化父类的构造函数*/
    }
}
var w=new Web('李四');
alert(w.run());

4、多态(属于继承)

//多态:父类定义一个方法不去实现,让继承它的子类去实现  每一个子类有不同的表现 
class Animal {
    name:string;
    constructor(name:string) {
        this.name=name;
    }
    //具体吃什么?继承它的子类去实现 ,每一个子类的表现不一样
    eat(){
        console.log('吃的方法')
    }
}

class Dog extends Animal{
    constructor(name:string){
        super(name)
    }
    eat(){
        return this.name+'吃狗粮'
    }
}

class Cat extends Animal{
    constructor(name:string){
        super(name)
    }
    eat(){
        return this.name+'吃鱼'
    }
}

5、静态属性及方法

//属性及方法前面加static,就是静态属性及方法
class Person{
    public name:string;
    static age = 20 //静态属性
    constructor(name:string){
        this.name = name;
    }
    //实例方法
    run(){
        console.log(`${this.name}在运动`)
    }
    //静态方法
    static work(){
        console.log(`我今年${Person.age}岁`)
    }
}
//调用实例化方法
var p = new Person('张三')
p.run();
//调用静态方法及属性
Person.work(); 
Person.age;

6、抽象方法

//类及方法前加关键词 abstract,就是抽象类及抽象方法
//抽象方法只能放在抽象类里面
abstract class Animal{
    public name:string;
    constructor(name:string){
        this.name = name;
    }
    //抽象方法不包含具体实现,并且必须在派生类中实现
    abstract eat():void;
}
class Dog extends Animal{
    constructor(name:string){
       super(name)
    }
    //抽象类的子类必须实现抽象类里面的抽象方法
    eat(){
        console.log(this.name + '吃粮食')
    }
}
var d = new Dog('小狗');
d.eat();

猜你喜欢

转载自www.cnblogs.com/MaShuai666/p/12356909.html