TypeScript类的静态属性,静态方法,抽象类
ES5中的静态方法
function Person() { } // 定义静态方法 Person.run = function() { console.log("我在运动") } Person.run(); // 调用静态方法
TypeScript 定义静态方法 使用关键字 static
class Person{ public name:string; public age:number; // 构造函数, 实例化类时触发的方法 constructor(name:str
ing, age:number) { this.name = name; this.age = age; } // 定义方法 run():void { console.log(this.name + "在运动"); } // 类属性的get,set方法 getName():string{ return this.name; } setName(name:string):void{ this.name = name; } getAge():number{ return this.age; } setAge(age:number):void{ this.age = age; } // 定义静态方法 static print():void { console.log("这个是静态方法"); } } var p = new Person("张三", 20); p.run(); // 实例方法 // 调用静态方法 Person.print(); // 输出: 这个是静态方法
静态方法,无法使用非静态的属性
静态属性
// typeScript 类 class Person{ public name:string; public static age:number; // 构造函数, 实例化类时触发的方法 constructor(name:string) { this.name = name; } // 定义方法 run():void { console.log(this.name + "在运动"); } // 类属性的get,set方法 getName():string{ return this.name; } setName(name:string):void{ this.name = name; } // 定义静态方法 static print():void { console.log("这个是静态方法" + this.age); } } var p = new Person("张三"); p.run(); // 实例方法 Person.age = 30;// 赋值给静态属性 Person.print(); // 输出: 这个是静态方法30
实例化的对象无法调用静态方法和属性
我们可以这样修改这个实例方法调用静态属性, 通过静态调用方法调用, 这样就不会报错了
Typescript的多态
多态指:父类去定义方法不去实现,让子类去继承实现方法,实现每一个子类都有不同的表现
继承属于多态的一种
继承
class Animal{ public name:string; constructor(name:string) { this.name = name; } play():void{ // 这个方法具体的实现,交给子类去实现,每一个子类的实现都不一样 console.log("在玩耍"); } }
class Dog extends Animal{ constructor(name: string){ super(name); } // 重写父类方法 play() { return this.name + "在玩小球"; } } class Cat extends Animal{ constructor(name: string){ super(name); } // 重写父类方法 play() { return this.name + "在玩铃铛"; } }
抽象类和抽象方法
// 定义抽象类, 定义标准
抽象类无法实例化
子类继承抽象类
abstract class Animal{ public name:string; constructor(name:string) { this.name = name; } abstract eat():any; } class Dog extends Animal{ constructor(name:string){ super(name); }
// 继承抽象类,必须实现抽象类的抽象方法
eat() {
console.log(this.name + "在吃东西");
}
}
var d = new Dog("小花花"); d.eat();
如果子类不去实现父类的抽象方法出现报错
如果抽象类里面有普通方法, 子类可以不去实现,也可以调用父类的方法,并且子类也可以定义自己的方法
abstract class Animal{ public name:string; constructor(name:string) { this.name = name; } abstract eat():any; run(){ console.log("抽象类的普通方法内容"); } } class Dog extends Animal{ constructor(name:string){ super(name); } // 继承抽象类,必须实现抽象类的抽象方法 eat() { console.log(this.name + "在吃东西"); } // 子类自己的方法 play(){ console.log(this.name + "在玩耍"); } } var d = new Dog("小花花"); d.eat(); d.run(); d.play();