JavaScript中设置器和获取器

在JavaScript中,setters 和 getters 是对象属性的特殊方法,用于定义如何访问和设置对象的属性。这些方法使得可以在对对象属性执行读取或写入操作时添加自定义逻辑。

举例

首先我们定义一个类似之前银行家的一个对象

const account = {
  owner: 'ITshare',
  movements: [100, 1200, 550, 130],

  get latest() {
    return this.movements.slice(-1).pop();
  },

  set latest(mov) {
    this.movements.push(mov);
  },
};
console.log(account.latest);
account.latest = 50;
console.log(account.movements);

在这里插入图片描述

实例

我们可以在之前的构造函数上去使用这个属性

class PersonCl {
  constructor(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  }

  cacleAge() {
    console.log(2037 - this.birthYear);
  }

  greet() {
    console.log(`Hey ${this.firstName}`);
  }

  get age() {
    return 2037 - this.birthYear;
  }
}

const ITshare = new PersonCl('ITshare', 1998);
console.log(ITshare);
ITshare.cacleAge();
console.log(ITshare.age);

console.log(ITshare.__proto__ === PersonCl.prototype);

在这里插入图片描述

● 不仅如此,setter还可以作为数据验证使用

class PersonCl {
  constructor(fullName, birthYear) {
    this.fullName = fullName;
    this.birthYear = birthYear;
  }

  cacleAge() {
    console.log(2037 - this.birthYear);
  }

  greet() {
    console.log(`Hey ${this.firstName}`);
  }

  get age() {
    return 2037 - this.birthYear;
  }

  set fullName(name) {
    if (name.includes(' ')) this._fullName = name;
    else alert(`!!!请输入你的全名`);
  }
}

const ITshare = new PersonCl('ITshare', 1998);
console.log(ITshare);

在这里插入图片描述这样并不会创建这个用户
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值