#TS# get/set

class Person {
    constructor() {
    }
    private _name: string;

    public get name() {
        return this._name;
    }

    public set name(name: string) {
        this._name = name;
    }
}

let person = new Person();

// person._name = "apple";  // 无法访问到_name变量

person.name = "apple";

console.log(person.name);  // 输出 apple  

就是为了隔离类的自有属性和可暴露属性。 

猜你喜欢

转载自www.cnblogs.com/tianmuxi/p/9164397.html