“This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

There are two types of object properties, and the ones we use are called data properties; There are also accessor properties, which are essentially functions to get and set values, but look like regular properties from external code.

“Getter” and “setter”

For example, we have an object user with name and surname attributes

let user = {
  name: "John",
  surname: "Smith"
};
Copy the code

If you now also want to add a fullName attribute whose value consists of name and surname, you can do so

The above we can have access to the user. The fullName value, can normal read: because a getter to run behind the scenes. But when you try to assign this new property

You will notice an error because the current fullName only has a getter. (Note that this error is not displayed if it is not in strict mode);

So if you want to assign, you should put a setter in there

let user = { name: "John", surname: "Smith", get fullName() { return `${this.name} ${this.surname}`; }, set fullName(value) { [this.name, this.surname] = value.split(" "); }};Copy the code

Now you can try the results again

In this way, a “virtual” property is implemented that is readable and writable.


Accessor descriptor

We have already said what the descriptors of properties are. Is the descriptor for accessor properties the same as the descriptor for data properties?

The answer is: no.

For accessor properties, there is no value and writable, but there are get and set functions.

So accessor descriptors might have:

  • Get — a function with no arguments that works when reading properties,
  • Set — a function with one argument, called when the property is set,
  • Enumerable — Same as a data attribute,
  • Different — the same as the data attribute.

Advanced use of “getters” and “setters”

You can also restrict values by using getters/setters as wrappers for “real” property values.

Example 1: If you want to disallow too short user names, create a setter name and store the value in a separate property _name, i.e

let user = { get name() { return this._name; }, set name(value) {if (value.length < 4) {console.log(" too many names, at least 4 characters "); return; } this._name = value; }};Copy the code

At this point you’re setting name

As you can see, the setting succeeds only when the conditions are met.

In the example, name is stored in the _NAME property and is accessed through the getter and setter. Technically, external code can access name directly using user._name. However, there is a well-known convention that attributes starting with an underscore “_” are internal and should not be accessed from outside the object.

You can also control and adjust the behavior of “normal” data properties by replacing them with getters and setters.

Example 2: Suppose you start implementing the User object using the data attributes name and age

Now you don’t want age, you want birthday

Now, the question is, what about the age property we used before?

You could find all the ages and change it, but obviously that would be too much trouble. At this point you can use the getter to solve gracefully

function User(name, birthday) { this.name = name; this.birthday = birthday; DefineProperty (this, "age", {get() {let todayYear = new Date().getFullYear(); return todayYear - this.birthday.getFullYear(); }}); }Copy the code

Now not only have you successfully added birthday, but age is still accessible.

conclusion

getter

The GET syntax binds an object property to the function that will be called when the property is queried.

Grammar:

{get prop() { ... } } {get [expression]() { ... }}Copy the code

Getter Usage Scenarios

  • You need to allow access to properties that return dynamically computed values.

  • You need to reflect the state of internal variables without using explicit method calls.

setter

When you try to set a property, the set syntax binds the object property to the function to be called.

Grammar:

{set prop(val) { . . . }}
{set [expression](val) { . . . }}
Copy the code

Setter usage scenarios

  • Try changing the value of a pseudo-attribute. (Like fullName in our example above)

References:

MDN getter

MDN setter

Property getters and setters


🎨 [thumbs up] [concerns] don’t get lost, more front-end dry goods waiting for you to unlock

Phase to recommend

👉 Product, technology, design and other areas of the Internet “basic terms” literacy

👉 Web security defense means are here!

👉 7 types of JavaScript to fill in the gaps!

👉 JavaScript deep copy and shallow copy read this article is enough!