编程 JavaScript中设置器和获取器

2024-11-17 19:54:27 +0800 CST views 700

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

举例

首先我们定义一个类似银行账户的对象,通过gettersetter访问属性:

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); // 输出最后一笔交易:130
account.latest = 50; // 添加新的交易
console.log(account.movements); // 输出所有交易:[100, 1200, 550, 130, 50]

在这个例子中,latest 是一个获取器(getter),它获取交易列表的最后一项。我们还使用了设置器(setter)来向交易列表中添加新交易。

实例

我们可以在类中使用gettersetter,比如在之前的构造函数中应用这些属性:

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

  calcAge() {
    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 对象
ITshare.calcAge(); // 计算并输出年龄
console.log(ITshare.age); // 使用getter获取年龄
console.log(ITshare.__proto__ === PersonCl.prototype); // 验证原型链

在这个例子中,我们为 PersonCl 类添加了一个 get 方法 age,它根据出生年份计算当前年龄。通过 getter 方法可以像访问普通属性一样使用 age,而不需要像函数那样调用。

Setter 进行数据验证

setter 方法不仅可以设置属性,还可以进行数据验证。如下所示,我们可以在 PersonCl 类中验证传入的名字是否为全名:

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

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

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

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

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

  get fullName() {
    return this._fullName;
  }
}

const ITshare = new PersonCl('ITshare', 1998);
console.log(ITshare); // 输出用户信息,如果名字不包含空格则弹出警告

在这个例子中,我们使用了 set fullName 进行数据验证,确保输入的姓名包含空格,否则弹出提示框提醒用户输入全名。通过这种方式,setter 方法可以在设置属性时进行逻辑验证。


以上就是在 JavaScript 中使用 gettersetter 的简单介绍,它们可以使对象属性的访问和修改更加灵活,甚至可以在属性的读写中引入复杂的业务逻辑或数据验证。

复制全文 生成海报 编程 JavaScript 面向对象编程

推荐文章

JavaScript 的模板字符串
2024-11-18 22:44:09 +0800 CST
html一份退出酒场的告知书
2024-11-18 18:14:45 +0800 CST
js常用通用函数
2024-11-17 05:57:52 +0800 CST
Nginx 反向代理 Redis 服务
2024-11-19 09:41:21 +0800 CST
js生成器函数
2024-11-18 15:21:08 +0800 CST
前端开发中常用的设计模式
2024-11-19 07:38:07 +0800 CST
【SQL注入】关于GORM的SQL注入问题
2024-11-19 06:54:57 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
Elasticsearch 的索引操作
2024-11-19 03:41:41 +0800 CST
一个简单的打字机效果的实现
2024-11-19 04:47:27 +0800 CST
使用 node-ssh 实现自动化部署
2024-11-18 20:06:21 +0800 CST
MySQL设置和开启慢查询
2024-11-19 03:09:43 +0800 CST
FcDesigner:低代码表单设计平台
2024-11-19 03:50:18 +0800 CST
Vue3中如何实现国际化(i18n)?
2024-11-19 06:35:21 +0800 CST
Go 1.23 中的新包:unique
2024-11-18 12:32:57 +0800 CST
程序员茄子在线接单