编程 JavaScript中设置器和获取器

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

在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 面向对象编程

推荐文章

Golang Select 的使用及基本实现
2024-11-18 13:48:21 +0800 CST
任务管理工具的HTML
2025-01-20 22:36:11 +0800 CST
html一些比较人使用的技巧和代码
2024-11-17 05:05:01 +0800 CST
LLM驱动的强大网络爬虫工具
2024-11-19 07:37:07 +0800 CST
Manticore Search:高性能的搜索引擎
2024-11-19 03:43:32 +0800 CST
Nginx 实操指南:从入门到精通
2024-11-19 04:16:19 +0800 CST
对多个数组或多维数组进行排序
2024-11-17 05:10:28 +0800 CST
Git 常用命令详解
2024-11-18 16:57:24 +0800 CST
前端如何一次性渲染十万条数据?
2024-11-19 05:08:27 +0800 CST
ElasticSearch 结构
2024-11-18 10:05:24 +0800 CST
实现微信回调多域名的方法
2024-11-18 09:45:18 +0800 CST
支付轮询打赏系统介绍
2024-11-18 16:40:31 +0800 CST
程序员茄子在线接单