class Person { constructor(private _name: string){} // 對於私有的屬性進行處理后再暴露出去,比如加密,確保安全 get name(){ return this._name + ' hi'; } // 外層無法直接賦值,通過 set 賦值 set name(name: string){ const realName = name.split(' ')[0] this._name = realName } } const person = new Person('zina'); console.log(person.name); // get 的寫法,不需要用括號 person.name = 'zina hi'; console.log(person.name);
通過 Getter 和 Setter 保護住私有屬性
/** * 單例模式,只允許有一個類的設計模式 * 不希望出現 const demo1 = new Demo() * const demo2 = new Demo() * 希望永遠只有一個實例,要怎么限制 * private constructor(){} */ class Demo{ private static instance: Demo; private constructor(public name:string){} // static 表示這個方法直接掛在類傻上,而不是類的實例上面 static getInstance(){ if(!this.instance){ this.instance = new Demo('danli') } return this.instance; } } const demo1 = Demo.getInstance(); const demo2 = Demo.getInstance(); console.log(demo1.name, demo2.name); // 其實這兩個是相等的,這樣就創建了一個單例
