• 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);
    // 其实这两个是相等的,这样就创建了一个单例
  • 相关阅读:
    vue.js 第二课
    vue.js学习(第一课)
    2016-11-14看张大神的微博总结
    这几天的工作总结:
    调了一天的兼容总结下
    鸭式辩论
    prototype 原型
    前端ps常用的小技巧
    Android的开始之相对布局
    Android的开始之线性布局
  • 原文地址:https://www.cnblogs.com/wzndkj/p/13041243.html
Copyright © 2020-2023  润新知