// 类里面的修饰符 typescript提供三种修饰符
/*
public: 公有 在类里面、类外面、子类都可以访问 (默认不加就是public)
protected: 保护 在类里面和子类可以访问
private: 私有 在当前类可以访问别的都不可以访问
*/
// 类的静态属性 静态方法
/* es5中的写法 */
function Person () {
// this.run = function () {} // 实例方法
// this.run = ()=> {}
}
Person.run = function () {} // 静态方法
class Person1 {
name:string;
static sex = 'man'; // 静态属性
constructor(name: string) {
this.name = name;
}
eat() {
console.log(`${this.name}吃饭`)
}
static work() {
console.log(`这是一个静态方法` + Person1.sex)
// console.log(`${this.name}哈哈`) // 错误的写法,静态方法里面无法调用类的属性、方法。
}
}
var p = new Person1('aaa');
p.eat(); // 实例方法调用
Person1.work(); // 静态方法调用
// 多态:父类定义一个方法不去实现,让继承它的子类去实现
// typescript中的抽象类是提供其它类的基类,不能直接被实例化;
// 用abstract关键字定义的抽象方法和抽象类,不包括具体实现必须在派生类实现。
// 并且抽象方法只能放在 抽象类里面
// 抽象类用于定义标准
abstract class Animal {
abstract eat():void;
}
// var a = new Animal(); // 错误的写法抽象类不能被实例化。
class Dog extends Animal {
constructor() {
super()
}
eat () {
console.log('抽象类的子类必须实现抽象类的抽象方法')
}
}