Get and Set accessors in JavaScript. Explanation by example open

Get and Set accessors in JavaScript. Explanation by example

To mediate access to class properties, the latest JavaScript standards have added support for accessor methods. – get and set.

First, let’s look at a problem we might encounter:

    class Person {

        constructor(name, age) {
            this.name = name;
            this.age = age;

        }
    }

    const alex = new Person("Alexander", 33);

    console.log(alex.age);   // 33

    alex.age = -15;

    console.log(alex.age);  // -15

The Person class defines two properties – name (name) and age (age of the person), whose values we can get or set.

But what if we pass invalid values? So, in the example above, the age property is passed a negative number, but age cannot be negative.


    class Person {
        #ageValue = 1;

        constructor(name, age) {
            this.name = name;
            this.setAge(age);
        }

        getAge() {
            return this.#ageValue;
        }

        setAge(value) { if (value > 0 && value < 110) this.#ageValue = value; }
    }

    const alex = new Person("Alexander", 33);
    console.log(alex.getAge());  // 33

    alex.setAge(-15);

    console.log(alex.getAge());  // 33
    

Now the age is stored in the private field ageValue. When it is set in the setAge() method, the passed value is checked. And the setting happens only if the correct value is passed. And the getAge() method returns the value of this variable.

But there is another solution – the use of get and set accessors:

    // private field definition
    #field;


set field(value){
        this.#field = value;
    }
get field(){
        return this.#field;
    }

Both get and set methods have the same names. As a rule, they mediate access to some private field. Method set is for setting. It takes a new value as a parameter. Next, in the set method, we can perform a number of installation actions.

The get method is for getting a value. Here we can define some logic when returning a value.

    class Person {

        #ageValue = 1;

        constructor(name, age) {
            this.name = name;
            this.age = age;
        }

        set sage(value) {
            if (value > 0 && value < 110) this.#ageValue = value;
        }

        get sage() {
            return this.#ageValue;
        }

    }
    const alex = new Person("Alexander", 33);

    console.log(alex.sage);

    alex.sage = -15;//33

As you can see from the example, working with access methods is done in the same way as with regular properties.

That is, when alex.sage is accessed, the get method will actually work, which will return the value of the ageValue field. And when call alex.age = -15; set method will work.

Above, both get and set methods were used, respectively, the value of the field could be both obtained and set. However, in reality we can only use one of them. For example, we can leave only the get method and thus do property is read-only.

Properties without accessing fields

It’s worth noting that the get and set methods don’t have to access private or non-private fields. This may also be computed properties. For example:

    class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
        get fullName() { return `${this.firstName} ${this.lastName}` }
    }
    const alex = new Person("Alexander", "Thomson");
    console.log(alex.fullName); // Alexander Thomson
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation