Skip to content

属性的类别

  • public 公共
  • private 私有
  • protected 受保护的属性
typescript
class Person{
    // 默认的属性是 public, 可以公共访问和修改
    // 当我们加上 private 关键字时,表示属性只可以在类内部去访问
    private name:string
    public age:number
    constructor(name:string,age:number) {
        this.name = name
        this.age = age
    }
    getName(){
        return this.name
    }
    setName(value:string){
        this.name = value
    }
}

const per = new Person("小米",22)
per.setName("达达")

console.log(per);

当我们定义了一个 get和set时,对象的属性的控制权就完全掌握在我们的手中,想给对象什么值,就可以给什么值,不想给什么值就可以不给。


他们被称为属性的存取器

TS中的getter和setter

typescript
class Person{
    private _name:string
    public _age:number
    constructor(name:string,age:number) {
        this._name = name
        this._age = age
    }
    // TS 中设置 getter方法 的方式
    get name(){
        return this._name
    }
    set name(value:string){
        this._name = value
    }
}

const per = new Person("小米",22)
// TS 中使用 getter 的方式
console.log(per.name)
per.name = '大米'
console.log(per);

private

typescript
class A{
    private name:string
    constructor(name:string) {
        this.name = name
    }
}

class B extends A{
    sayHello(){
        // 此处访问不了父类的 name
        console.log(this.name)
    }
}
const b = new B('小米')
console.log(b);

快捷写法

typescript
//简便写法
class C{
    constructor(public name:string,public age:number) {
    }
}

// 完整写法
class C{
    name:string;
    age:number;
    constructor(name:string,age:number) {
        this.name = name
        this.age = age
    }
}

const c = new C('小米',22)
console.log(c);