美文网首页
getter和setter

getter和setter

作者: 恍若如梦hzpeng | 来源:发表于2020-05-27 09:05 被阅读0次

    getter和setter

    class Person {
      constructor(private _name: string) {}
    
      get name() {
        return this._name;
      }
    
      set name(name: string) {
        this._name = name;
      }
    }
    
    const person = new Person('Hzp');
    console.log(person.name);
    person.name = 'Huangzhenpeng';
    console.log(person.name);
    
    

    单例模式实现

    class Person {
      private constructor(public name: string) {}
    
      private static instance = Person ;
      static getInstance(name: string) {    // static挂载类上的属性,而不是类的实例上
        if (!this.instance) {
          this.instance = new Person(name);
        }
        return this.instance;
      }
    }
    
    const person1 = Person.getInstance('Huang');
    const person2 = Person.getInstance('Hzp');
    console.log(person1.name);  // Huang
    console.log(person2.name);  // Huang
    

    相关文章

      网友评论

          本文标题:getter和setter

          本文链接:https://www.haomeiwen.com/subject/dbmiahtx.html