初学TypeScript04(typescript中的类)

135 阅读2分钟

类的定义

class Person {
    name:string; //如果直接定义属性 默认修饰符为public 相当于 public name:string
    constructor(name:string) { //构造函数 实例化类的时候触发的函数
        this.name=name
    }
    run():void{
        console.log(this.name)
    }
    setName(name:string):void{
        this.name=name
    }
    getName():string{
        return this.name
    }
}
var p = new Person('小明')
p.run()
p.setName('小红')
console.log(p.getName())

类的继承(extends super关键字)

class Person {
    name:string; //如果直接定义属性 默认修饰符为public 相当于 public name:string
    constructor(name:string,age:number) { //构造函数 实例化类的时候触发的函数
        this.name=name
    }
    run():void{
        console.log(this.name+"在运动")
    }
}
class Web extends Person {
    constructor(name:string) {
        super(name,18)  // super(...) 相当于父类的constructor函数 调用父构造函数
    }                   //使用 super.method(...) 调用父方法 例如 super.run()
}
var w = new Web('xiaoming')
w.run()

类里面的修饰符

typescript里面定义属性的时候给我们定义了3种修饰符

  • public 公有 在当前类里面 子类 类外面都可以访问
class Person {
    public name:string; //公有属性
    constructor(name:string,age:number) { //构造函数 实例化类的时候触发的函数
        this.name=name
    }
    run():void{
        console.log(this.name+"在运动") //自己类里面访问
    }
}
class Web extends Person {
    constructor(name:string) {
        super(name,18)      
    }
    work():void{
        console.log(this.name+"在工作") //子类访问name
    }                   
}
var w = new Web('xiaoming')
w.work() 
//类外部访问公有属性
var p = new Person('小花',18)
console.log(p.name)
  • protected 保护 在当前类里面 子类 都可以访问 类外面不可访问
class Person {
    protected name:string; 
    constructor(name:string,age:number) { //构造函数 实例化类的时候触发的函数
        this.name=name
    }
    run():void{
        console.log(this.name+"在运动") //自己类里面访问
    }
}
class Web extends Person {
    constructor(name:string) {
        super(name,18)      
    }
    work():void{
        console.log(this.name+"在工作") //子类访问name
    }                   
}
var w = new Web('xiaoming')
w.work() 
//类外部访问公有属性
var p = new Person('小花',18)
console.log(p.name) // 语法报错
  • private 私有 在当前类里面 可以访问 子类 类外面都不可以访问
class Person {
    private name:string; 
    constructor(name:string,age:number) { //构造函数 实例化类的时候触发的函数
        this.name=name
    }
    run():void{
        console.log(this.name+"在运动") //自己类里面访问
    }
}
class Web extends Person {
    constructor(name:string) {
        super(name,18)      
    }
    work():void{
        console.log(this.name+"在工作") //报错 属性“name”为私有属性,只能在类“Person”中访问
    }                   
}
var w = new Web('xiaoming')
w.work()
//类外部访问公有属性
var p = new Person('小花',18)
console.log(p.name) // 语法报错