zoukankan      html  css  js  c++  java
  • 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);
    // 其实这两个是相等的,这样就创建了一个单例
  • 相关阅读:
    KnockoutJS(2)-监控属性
    KnockoutJS(1)-数据模型
    Stimulsoft Reports报表工具
    Knockout.js 初探
    web网页的表单排版利器--960css
    用一个div模拟textarea的实现
    正则表达式笔记4-封装class
    正则表达式笔记3
    正则表达式笔记2
    正则表达式笔记1
  • 原文地址:https://www.cnblogs.com/wzndkj/p/13041243.html
Copyright © 2011-2022 走看看