TypeScript学习笔记四 理解类的代码

官网教程: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

最后一行会报错:

 

两个实例不兼容

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值