TypeScript 中「类」的基本使用

80 阅读1分钟

1、es 5 中类的定义

function Person(){          //es5中简单的类
    this.name = '张三';     //属性
    this.age = 20;

    this.run = function(){ //实例方法:通过 new 的实例来调用
        alert(`${this.name}快点跑啊!`);
    }
}
Person.prototype.work = function(){    //原型方法:实例会共享这个方法
    alert(`${this.name}加班工作!`);
}
Person.eat = function(){ alert('静态方法'); }    //静态方法
let person = new Person();    //类的实例化
alert(person.name);
person.run();
person.work();
Person.eat();

2、TypeScript 中类的定义

class Person{
    name:string;    //属性    前面省略了 public 关键字
    
    constructor(name:string){  //构造函数    实例化的时候触发的方法
        this.name = name;
    }

    getName(){ return this.name; }
    setName(name){ this.name = name; }
}
let person = new Person('孙悟空');    //类的实例化
person.getName();

3、es 5 中类的继承

function Animal(){}
function Dog(){
    Animal.call(this);    //将 Animal 中的 this 指向 Dog 的实例
}

function temp(){}
temp.prototype = Animal.prototype;
Dog.prototype = new temp();
Dog.prototype.constructor = Dog;

4、TypeScript 中类的继承

class Person{
    name:string;    //属性    前面省略了 public 关键字
    
    constructor(name:string){  //构造函数    实例化的时候触发的方法
        this.name = name;
    }

    getName(){ return this.name; }
    setName(name){ this.name = name; }
}

class Child extends Person{    //子类继承父类,子类的实例可以调用符类中的方法
    constructor(name:string){
        super(name);
    }
}

5、类里面的修饰符

typescript 里面定义属性的时候给我们提供了三种修饰符:public、protected、private。

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