为什么要在JavaScript中使用getter和setter? [英] Why use getters and setters in JavaScript?

查看:89
本文介绍了为什么要在JavaScript中使用getter和setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JavaScript中的getter和setter如何工作.我不明白的是为什么在使用常规函数可以获得相同结果时为什么需要它们?考虑以下代码:

I know how getter and setter work in JavaScript. What I don't understand is why we need them when we can get the same result using normal functions? Consider the following code:

var person = {
    firstName: 'Jimmy',
    lastName: 'Smith',
    get fullName() {
        return this.firstName + ' ' + this.lastName;
    }
}

console.log(person.fullName);    // Jimmy Smith

我们可以轻松地将getter替换为一个函数:

We can easily replace getter with a function:

var person = {
    firstName: 'Jimmy',
    lastName: 'Smith',
    fullName: function() {
        return this.firstName + ' ' + this.lastName;
    }
}

console.log(person.fullName());    // Jimmy Smith

我看不到写getter和setter的意义.

I don't see the point of writing getter and setter.

推荐答案

使用getter或setter与使用标准函数之间的区别在于,getter/setter在赋值时自动被调用.因此,它看起来就像一个普通属性,但在幕后您可以在分配之前或之后运行额外的逻辑(或检查).

A difference between using a getter or setter and using a standard function is that getters/setters are automatically invoked on assignment. So it looks just like a normal property but behind the scenes you can have extra logic (or checks) to be run just before or after the assignment.

因此,如果您决定将这种额外的逻辑添加到已被引用的现有对象属性之一中,则可以将其转换为getter/setter样式,而无需更改有权访问该属性的其余代码.

So if you decide to add this kind of extra logic to one of the existing object properties that is already being referenced, you can convert it to getter/setter style without altering the rest of the code that has access to that property.

这是一个额外逻辑的示例,该类计算其名称被读取的次数:

Here is an example for an extra logic, this class counts how many times its name is read:

class MyClass {
  constructor() {
    this.refCount = 0;
    this._name = 'the class';
  }

  get name() {
    this.refCount++;
    console.log(`name is read ${this.refCount} times.`);
    return this._name;
  }
}

const myClass = new MyClass();

let maxMessages = 5;
const t = setInterval(() => {
  console.log(`name: ${myClass.name}`);
  
  if (--maxMessages < 1) {
    console.log('done');
    clearInterval(t);
  }
}, 1000);

这篇关于为什么要在JavaScript中使用getter和setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆