“类的成员属性”都是实例属性,而不是原型属性,“类的成员方法”都是“原型”方法。
类的成员修饰符有:public,private,protected,readonly,static
class Cat{
constructor(name:string,age?:number){
this.name=name
this.age=age
}
name:string
age?:number
leap(){}
private miao(){
return 'miaomiao'
}//私有属性不能在实例和子类中调用
protected sterilizate(){
return this.miao()+" can't sterilizate"
}//受保护成员只能在类和子类中调用
readonly legs:number=4//只读属性不能修改,所以一定要被初始化
static food:string='fish'//静态成员只能通过类来调用,不能通过实例来调用
}
class BritishShorthair extends Cat{
constructor(name:string, public gender:string,age?:number,color:string='stripe gray',){//修饰符也可以用于参数,比如gender就变为了实例属性
super(name,age)
this.color=color
}
color?:string
getInformation(){
console.log(this.sterilizate())
}
}
log(Cat.food)
let cat1=new BritishShorthair('lucy','male')
// log(cat1.food)
// log(cat1)
cat1.getInformation()
抽象类
作用:提取共性、实现多态
js中并没有这个概念,ts
只能被继承,不能被实例化的类
ts中的多态:
//抽象类,只能被继承,不能实例化的类
//关键字:abstract
abstract class Animal{
eat(){
console.log('eat')
}
abstract sleep():void
}
class Dog extends Animal{
constructor(){
super()
}
sleep(){
console.log('dog sleep')
}
}
class Rabbit extends Animal{
constructor(){
super()
}
sleep(){
console.log('rabbit sleep')
}
}
let dog=new Dog()
let rabbit=new Rabbit()
let animals:Animal[]=[dog,rabbit]
animals.forEach((item)=>{
item.sleep()
})//实现多态
this
利用return this 可以实现链式调用
class Workflow{
step1(){
console.log('step1')
return this
}
step2(){
console.log('step2')
return this
}
}
new Workflow().step1().step2()
class Myflow extends Workflow{
next(){
console.log('next')
return this
}
}
new Myflow().next().step2().next().step1()
接口和类的关系
//类类型接口
interface Human{
name:string
eat():void
}
//implement 关键字 类必须定义接口中的所有属性;接口只能约束类的公有(public)成员
class Asian implements Human{
constructor(name:string){
this.name=name
}
name:string
eat(){}
claim(){}
}
//接口继承接口
interface Man extends Human{
run():void
}
interface Child{
cry():void
}
interface Boy extends Man,Child{
naughty():void
}
let littleBay:Boy={
name:"tom",
eat(){},
run(){},
cry(){},
naughty(){}
}
//接口继承类
class Auto{
state=1
}
interface AutoInterface extends Auto{
}
class C implements AutoInterface{
state=1
}
class Bus extends Auto implements AutoInterface{//不用声明state了
}
接口和类的关系.png
网友评论