官网教程:https://www.tslang.cn/docs/handbook/classes.html
理解类的代码:
class Animal{
name:string
private fierce:number
constructor(animal:string,fierce=0){
this.name = animal
this.fierce = fierce
}
setName(animalName:string){
this.name = animalName
}
getName():string{
return this.name
}
getPrivate():number{
return this.fierce
}
running(){
return "Little animal is running..."
}
}
class Dog extends Animal{
bark(){
return "Woof!Woof!"
}
}
class Cat extends Animal{
bark(){
return "Miao!Miao!"
}
}
class Horse extends Animal{
constructor(name:string,legs:number = 4){
super(name)
}
running(){
return "Little horse is running"
}
}
// 继承
let cat = new Cat("JiaFei",3)
console.log("这只小猫名字是:" + cat.name + " 这只小猫这样叫: " + cat.bark())
console.log("小猫跑-》" + cat.running())
console.log("小猫的凶狠程度是: " + cat.getPrivate() + " 颗星")
// 继承
let horse = new Horse("Jack Ma")
console.log("这只小马的名字是: " + horse.getName() + "小马跑-》 " + horse.running())
console.log("小马的凶狠程度是: " + horse.getPrivate() + " 颗星")
// 类型兼容
let animal = new Animal("Bear")
animal = horse
console.log("这个动物是: " + animal.name)
// 有private 则类型不兼容
class Wood{
type: string
private price: number
}
class Desk{
type: string
private price: number
}
let wood = new Wood()
let desk = new Desk()
wood = desk
最后一行会报错:
两个实例不兼容