ts基础 - 类定义
ts语言特征:封装,继承,多态,抽象
1.class的定义
class Person {
name: string;
constructor(n: string) {
this.name = n;
}
getName():string {
return this.name;
}
setName(name:string):void {
this.name = name;
}
}
var p = new Person('张三');
console.log(p.getName()); //张三
console.log(p.setName('李四')); //李四
2.ts中实现继承 extends super
class Person { name: string; constructor(name: string) { this.name = name; } run(name:string):void { this.name = name; } } class Web extends Person{ constructor(name: string) { super(name) //初始化父类的构造函数 } } var P = new Web('张三') //不报错
注意:如果没有 super(name) 会报错
3.ts中实现继承,子类添加方法;
class Person { name: string; constructor(name: string) { this.name = name; } run(name:string):void { this.name = name; } } class Web extends Person{ constructor(name: string) { super(name) //初始化父类的构造函数 } work():void{ console.log(this.name + '在工作') } } var P = new Web('张三') P.work(); //张三在工作
4.ts中实现继承,父类方法和子类方法有一样的方法;
class Person { name: string; constructor(name: string) { this.name = name; } run(name:string):void { this.name = name; } work():void{ console.log(this.name + '在跑步') } } class Web extends Person{ constructor(name: string) { super(name) //初始化父类的构造函数 } work():void{ console.log(this.name + '在工作') } } var P = new Web('张三') P.work(); //张三在工作
注意:先子类里面找方法,子类里面没有在往父类里面找方法
5.ts类里面的修饰符,三种:
public:共有(默认);在类里面,子类,类外面都可以访问
protected:保护类型;在类里面,子类可以访问
private:私有;在类里面可以访问
6.ts类的静态属性和静态方法
class Person { name: string; static age: number = 20; constructor(name: string) { this.name = name; } run(name:string):void { this.name = name; } static work() { console.log('静态方法') console.log(this.name) //报错 静态方法里面没法调用this属性 console.log(this.age) //不报错 静态方法里面可以调用静态属性 } } Person.age = 30; Person.work();
7.多态:父类定义一个方法不去实现,让继承它的子类去实现不同的表现,多态属于继承
class Animal { name: string; constructor(name: string) { this.name = name; } eat(){ //具体吃什么由它的子类去实现 console.log('吃什么') } } class Dog extends Animal { constructor(name: string) { super(name) } eat(){ console.log('小狗吃骨头') } } class Cat extends Animal { constructor(name: string) { super(name) } eat(){ console.log('小猫是鱼') } }
8.抽象方法:定义的一种标准
ts中的抽象类:它是提供其他的基础,不能直接被实例化; abstract抽象方法只能放在抽象类里面,子类里面没有
abstract class Animal { name: string; constructor(name: string) { this.name = name; } abstract eat():void; }
用abstract关键字定义抽象类和抽象方法,抽象类的抽象方法不包含具体的实现方法并且必须必须在子类去实现
class Dog extends Animal { constructor(name: string) { super(name) } eat(){ console.log('小狗吃骨头') } } class Cat extends Animal { constructor(name: string) { super(name) } eat(){ console.log('小猫是鱼') } }
可参考视频:https://www.bilibili.com/video/BV1yt411e7xV?p=7