class的get和set

一、使用场景

当我们需要在用户获取或设置实例某个属性的时候做一些附加的操作的时候,就能利用这个特性。

二、代码实现

  class Person {
    
    
    #name = ''
    #age = 0 // 设置私有属性存储值,避免被外部修改
    constructor(name, age) {
    
    
      this.#name = name
      this.#age = age
    }
    get age() {
    
    
      return this.#age
    }
    set age(val) {
    
    
      if (this.checkAge(val)) {
    
     // 设置前校验格式
        this.#age = val
      } else {
    
    
        console.warn('年龄不符合要求')
      }
    }
    checkAge(val) {
    
    
      return typeof val === 'number' && !(val < 0 || val > 150);
    }
  }
  const tom = new Person('tom', 12)
  tom.age = 45
  tom.age = 151
  console.log(tom.age)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43845090/article/details/133877469
今日推荐