编程 JavaScript中设置器和获取器

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

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

推荐文章

使用Vue 3实现无刷新数据加载
2024-11-18 17:48:20 +0800 CST
25个实用的JavaScript单行代码片段
2024-11-18 04:59:49 +0800 CST
Vue3中如何实现响应式数据?
2024-11-18 10:15:48 +0800 CST
记录一次服务器的优化对比
2024-11-19 09:18:23 +0800 CST
解决 PHP 中的 HTTP 请求超时问题
2024-11-19 09:10:35 +0800 CST
CSS 特效与资源推荐
2024-11-19 00:43:31 +0800 CST
mysql int bigint 自增索引范围
2024-11-18 07:29:12 +0800 CST
OpenCV 检测与跟踪移动物体
2024-11-18 15:27:01 +0800 CST
Go的父子类的简单使用
2024-11-18 14:56:32 +0800 CST
支付页面html收银台
2025-03-06 14:59:20 +0800 CST
pycm:一个强大的混淆矩阵库
2024-11-18 16:17:54 +0800 CST
如何在Vue3中定义一个组件?
2024-11-17 04:15:09 +0800 CST
html折叠登陆表单
2024-11-18 19:51:14 +0800 CST
使用 sync.Pool 优化 Go 程序性能
2024-11-19 05:56:51 +0800 CST
在 Nginx 中保存并记录 POST 数据
2024-11-19 06:54:06 +0800 CST
介绍Vue3的Tree Shaking是什么?
2024-11-18 20:37:41 +0800 CST
程序员茄子在线接单