编程 JavaScript中设置器和获取器

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

在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 中如何处理跨组件通信?
2024-11-17 15:59:54 +0800 CST
Vue3中的v-bind指令有什么新特性?
2024-11-18 14:58:47 +0800 CST
微信小程序热更新
2024-11-18 15:08:49 +0800 CST
Elasticsearch 监控和警报
2024-11-19 10:02:29 +0800 CST
如何在 Vue 3 中使用 Vuex 4?
2024-11-17 04:57:52 +0800 CST
Vue中的样式绑定是如何实现的?
2024-11-18 10:52:14 +0800 CST
Nginx 防盗链配置
2024-11-19 07:52:58 +0800 CST
如何将TypeScript与Vue3结合使用
2024-11-19 01:47:20 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
js迭代器
2024-11-19 07:49:47 +0800 CST
JavaScript设计模式:组合模式
2024-11-18 11:14:46 +0800 CST
php微信文章推广管理系统
2024-11-19 00:50:36 +0800 CST
程序员茄子在线接单