我无法理解 getter、setter

问题描述 投票:0回答:1

我很难理解 getter、setter。 我知道“get”用于访问属性,“set”用于更改或改变该属性。

但即使我将 _numOfSensors 更改为 -5 或“字符串”,它也不会给我错误消息......我一切都正确,但我一生都无法理解它是如何工作的。有人可以更准确、更简单地解释这段代码的工作原理吗?感谢所有帮助,保重!

语言:JavaScript

const robot = {
  _model: “1E78V2”,
  _energyLevel: 100,
  _numOfSensors: 15,
  get numOfSensors() {
    if (typeof this._numOfSensors === “number”) {
      return this._numOfSensors;
    } else {
      return “Sensors are currently down.”;
    }
  },
  set numOfSensors(num) {
    if (typeof num === “number” && num >= 0) {
    this._numOfSensors = num;
    } else {
      return “Pass in a number that is greater than or equal to 0”;
    }
  },
};
robot.numOfSensors = 100;
console.log(robot.numOfSensors);

嗯,我尝试过谷歌和网上查找,但我真的不明白......

get set
1个回答
0
投票

如果你尝试:

robot.numOfSensors = 100;
console.log(robot.numOfSensors);
robot.numOfSensors = -100;
console.log(robot.numOfSensors);
robot.numOfSensors = -5
console.log(robot.numOfSensors);
robot.numOfSensors = -17
console.log(robot.numOfSensors);

你会看到:

100
100
100
100

然后尝试:

robot.numOfSensors = -2;
console.log(robot.numOfSensors);
robot.numOfSensors = -5;
console.log(robot.numOfSensors);
robot.numOfSensors = 8
console.log(robot.numOfSensors);
robot.numOfSensors = -17
console.log(robot.numOfSensors);

您将得到:

100
100
8
8

这意味着 if 语句会产生一些差异,但是只有当您将函数的返回值分配给变量时,返回值才有意义

以我的拙见,您可以尝试抛出异常来代替它。

const robot = {
  _model: "1E78V2",
  _energyLevel: 100,
  _numOfSensors: 15,

  get numOfSensors() {
    if (typeof this._numOfSensors === "number") {
      return this._numOfSensors;
    } else {
      throw new Error("Sensors are currently down.");
    }
  },

  set numOfSensors(num) {
    if (typeof num === "number" && num >= 0) {
      this._numOfSensors = num;
    } else {
      throw new Error("Pass in a number that is greater than or equal to 0");
    }
  },
};

try {
  robot.numOfSensors = -5; // Trigger the setter, throw an exception
  console.log(robot.numOfSensors); // This line will not execute because exception is thrown
} catch (error) {
  console.log(error.message); // Catch the exception and print the error message
}

您可以在终端中看到输出:

Pass in a number that is greater than or equal to 0
© www.soinside.com 2019 - 2024. All rights reserved.