typescript中属性的封装,主要为了安全性

为什么要进行属性的封装,就是为了安全性,举个例子

class SX {
    
    
  name: string;
  age: number;
  constructor(name: string, age: number) {
    
    
    this.name = name;
    this.age = age;
  }
}

const sx = new SX('哈哈',12);
sx.name = '刘' 

name属性可以在外部任意被修改,会导致安全性低

介绍一个属性

private 私有属性,只能在类内部进行访问修改,通过在类中添加方法使得私有属性可以被外部访问,之前我们不写,默认就是public

然后我们这样写

class SX {
    
    
  private _name: string;
  private _age: number;
  constructor(name: string, age: number) {
    
    
    this._name = name;
    this._age = age;
  }

  //定义方法,获取属性
  getName(){
    
    
    return this._name;
  }
  //定义方法,设置name属性
  setName(value:string){
    
    
    this._name = value
  }
}

const sx = new SX('哈哈',12);
sx.setName('猪八戒')

现在修改方法在我手上,如果我不设置修改方法,那这个属性永远改不了

上面方式是我自己实现的,TS提供了更简便的方法

class SX {
    
    
  private _name: string;
  private _age: number;
  constructor(name: string, age: number) {
    
    
    this._name = name;
    this._age = age;
  }
  
  //获取属性方法,get
  get name(){
    
    
    return this._name;
  }
  //设置属性方法,set
  set name(value:string){
    
    
    this._name = value;
  }
}
const sx = new SX('哈哈',12);

sx.name; //获取
sx.name = '猪八戒'

除了public和private属性,ts还有一个protected属性

protected 受保护的属性,只能在当前类和当前类的子类里面调用

如何使用呢?

class protect{
    
    
  protected name : string;
  constructor(name : string){
    
    
    this.name = name;
  }
}
class protectchildren extends protect{
    
    
  getter(){
    
    
    console.log(this.name) //可以取到
  }
}

const aaa = new protectchildren('sss');
// aaa.name 取不到

最后再介绍一种写class简便的方法

之前这样写

class bbbb{
    
    
  public name : string;
  constructor(name : string){
    
    
    this.name = name;
  }
}

这样写就行,效果一样的

class bbbb{
    
    
  constructor(public name:string){
    
    }
}

最后再说一遍,封装是为了属性更安全,通过get和set修改

猜你喜欢

转载自blog.csdn.net/weixin_45389051/article/details/115285273