TypeScript Setter, Getter 和静态属性

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);
// 其实这两个是相等的,这样就创建了一个单例

 

posted @ 2020-06-04 06:45  wzndkj  阅读(1593)  评论(0编辑  收藏  举报