class P { constructor(private _name: string) {} // 私有属性一般用 _ 作为前缀 get name() { return this._name + '可以做一些操作'; } set name(name: string) { // 可以做一些保护 if (name.length > 10) { return; } this._name = name; }}const p = new P('zwx');p.name; // zwx可以做一些操作p.name = '1234567890000';p.name; // zwx可以做一些操作p.name = '1234';p.name; // 1234可以做一些操作
/*
* 单例模式
* 只能生成一个实例
*/
class Demo {
private static instance: Demo;
private constructor(private _name: string) {
this._name = _name;
} // 规避了 new 创建实例
get name() {
return this._name;
}
static getInstance(name: string) {
return this.instance ? this.instance : new Demo(name);
} // 把方法挂在类上,不是实例上
}
const demo = Demo.getInstance('zwx');
const demo2 = Demo.getInstance('pw');
demo.name // zwx
demo2.name // zwx