Javascript 简明教程

JavaScript - Object Accessors

JavaScript 中 object accessor 属性是获取或设置对象值的方法。它们使用 get 和 set 关键字定义。访问器属性是控制对象如何被访问和修改的强大方式。

The object accessor properties in JavaScript are methods that get or set the value of an object. They are defined using the get and set keywords. Accessor properties are a powerful way to control how your objects are accessed and modified.

JavaScript 对象可以具有两种属性。

The JavaScript object can have two kinds of properties.

  1. Data properties

  2. Accessor properties

以下属性称为数据属性。

The below property is called the data properties.

const obj = {
    key: "value", // Data property
}

Object Accessor Properties

在 JavaScript 中,您可以使用 getter 来获取对象属性,使用 setter 来设置对象属性。

In JavaScript, you can use the getters to get the object properties and setters to set the object properties.

定义 accessor 属性有两个关键字。

There are two keywords to define accessor properties.

  1. get − The get keyword is used to define a method to get the object property value.

  2. set − The set keyword is used to define a method to update the object property value.

JavaScript Getters

getters 用于访问对象属性。要将方法定义为 getter,我们使用 get 关键字,后跟方法名称。按照以下语法定义 getter。

The getters are used to access the object properties. To define a method as getter, we use get keyword followed by method name. Follow the syntax below to define the getter.

get methodName() {
     // Method body
}
obj.methodName;

在上面的语法中,我们使用 'get' 关键字定义 getter,后跟方法名称。

In the above syntax, we have defined the getters using the 'get' keyword followed by the method name.

您可以使用方法名称作为对象属性,以获得其返回值。

You can use the method name as an object property to get its returned value.

Example

在以下示例中,在 wall 对象中,我们定义了 getColor() getter。getColor() 返回 color 属性的值。

In the example below, in the wall object, we have defined the getColor() getters. The getColor() returns the value of the color property.

之后,我们使用 getColor() 方法访问对象的 color 属性值。

After that, we use the getColor() method to access the color property value of the object.

<html>
<body>
  <p id = "output">The color of the wall is : </p>
  <script>
    const wall = {
      color: "brown",
      get getColor() {
        return this.color;
      }
    }
    document.getElementById("output").innerHTML += wall.getColor;
  </script>
</body>
</html>
The color of the wall is : brown

JavaScript Setters

setters 用于更新 JavaScript 对象属性。要在 setter 中定义方法,使用 set 关键词,然后接方法名,按照以下语法在 JavaScript 对象中定义 setter:

The setters are used to update the JavaScript object properties. To define a method as setter, we use set keyword followed by method name You can follow the syntax below to define setters in the JavaScript object.

set methodName(param) { // Setter method
     return this.color = color;
}

wall.methodName = "Red";
  1. In the above syntax, the 'set' keyword is used to define the setter method.

  2. The method_name can be any valid identifier.

  3. The setter method always takes a single parameter. If you don’t pass a parameter or multiple parameters, it will give you an error.

  4. You can assign value to the setter method as you assign value to the property.

Example

在以下示例中,我们定义了 setter 方法,用于设置墙对象中 color 属性的值。我们使用“setColor”setter 方法为对象中的 color 属性设置“red”值。

In the example below, we have defined the setter method to set the value of the color property of the wall object. We set the 'red' value to the color property of the object using the 'setColor' setter method.

<html>
<body>
  <p id = "output"> </p>
  <script>
    const wall = {
      color: "brown",
      set setColor(color) {
        return this.color = color;
      }
    }
    document.getElementById("output").innerHTML +=
    "The color of the wall before update is : " + wall.color + "<br>";
    //updating the color of wall
    wall.setColor = "Red";
    document.getElementById("output").innerHTML +=
    "The color of the wall after update is : " + wall.color;
  </script>
</body>
</html>
The color of the wall before update is : brown
The color of the wall after update is : Red

JavaScript Object Methods vs. Getters/Setters

在 JavaScript 中,使用 getter 和 setter 可以做任何事情,你也可以通过定义特定的对象方法来完成。不同的是,getter 和 setter 提供了更简单的语法。

In JavaScript, whatever you can do using the getters and setters, you can also do by defining the specific object method. The difference is that getters and setters provide simpler syntax.

让我们通过一些示例来理解。

Let’s understand it with the help of some examples.

Example

在以下示例中,我们在墙对象中定义了 getColor() getter 方法和 colorMethod() 对象方法。两种方法都会返回颜色值。

In the example below, we have defined the getColor() getters method and colorMethod() object method in the wall object. Both method returns the color value.

你可以看到,定义和访问 getter 比定义和访问对象方法更简单。

You can observe that defining and accessing getters is more straightforward than defining and accessing the object method.

<html>
<body>
  <p id = "output"> </p>
  <script>
    const wall = {
      color: "brown",
      get getColor() {
        return this.color;
      },
      colorMethod: function () {
        return this.color;
      }
    }

    document.getElementById("output").innerHTML +=
    "Getting the color using the getters : " + wall.getColor + "<br>";

    document.getElementById("output").innerHTML +=
    "Getting the color using the object method : " + wall.colorMethod();
  </script>
</body>
</html>
Getting the color using the getters : brown
Getting the color using the object method : brown

Data Quality and Security

getter 和 setter 方法可以提供更好的数据质量。而且,它们用于封装,来保护对象数据。

The getter and setter methods can provide better data quality. Also, they are used for encapsulation to secure the object data.

让我们通过以下示例了解一下 getter 和 setter 如何提高数据质量并提供安全性。

Let’s understand how getter and setter improve data quality and provide security via the example below.

Example

在以下示例中,getColor() 是 getter 方法,它将 color 属性的值转换为大写形式并返回。另外,它将 color 属性对用户隐藏起来,因为你可以使用 getColor() 方法访问其值。

In the example below, the getColor() is a getter method, returning the value of the color property after converting it to the uppercase. Also, it hides the color property from users, as you can access its value using the getColor() method.

<html>
<body>
  <p id = "output"> </p>
  <script>
    const wall = {
      color: "Brown",
      get getColor() {
        return this.color.toUpperCase();
      }
    }
    document.getElementById("output").innerHTML +=
    "Getting the color using the getters : " + wall.getColor;
  </script>
</body>
</html>
Getting the color using the getters : BROWN

Defining getters/setters using the Object.defineProperty()

你还可以使用 Object.defineProperty() 方法向对象中添加 getter 或 setter。

You can also use the Object.defineProperty() method to add getters or setters into the object.

Object.defineProperty(object, "methodName", {
    keyword: function () {
        // Method body
    },
})

使用以上语法,你可以像 methodName 一样定义 getter 或 setter。

Using the above syntax, you can define the getter or setter same as methodName.

Parameters

  1. object − It is an object where you need to add getters or setters.

  2. methodName − It is the name of the method for getters or setters.

  3. keyword − It can be 'get' or 'set' according to you want to define the getter or setter method.

Example

在以下示例中,我们使用 object.defineProperty() 方法向对象添加了 getSize 和 setSize getter 和 setter。

In the example below, we have added the getSize and setSize getter and setter to the object using the object.defineProperty() method.

接下来,我们分别使用 getSize 和 setSize 来获取和设置大小。

After that, we use the getSize and setSize to get and set the size, respectively.

<html>
<body>
  <p id = "demo"> </p>
  <script>
    const output = document.getElementById("demo");
    const door = {
      size: 20,
    }
    Object.defineProperty(door, "getSize", {
      get: function () {
        return this.size;
      }
    });

    Object.defineProperty(door, "setSize", {
      set: function (value) {
        this.size = value;
      },
    })

    output.innerHTML += "Door size is : " + door.getSize + "<br>";
    door.setSize = 30;
    output.innerHTML += "Door size after update is : " + door.getSize;
  </script>
</body>
</html>
Door size is : 20
Door size after update is : 30

Reasons to use getters and setters

以下是 JavaScript 中使用 getter 和 setter 的优势。

Here are the benefits of using the getters and setters in JavaScript.

  1. It has a simple syntax than object methods.

  2. To improve the data quality by validating the data.

  3. For the encapsulation or securing the data.

  4. It also allows abstraction or data hiding.