Using getters and setters

JS now lets you define dynamic properties that, instead of being a stored value in the object, are calculated on the spot. For example, with the previous Person class, we could have a getter for lastFirst, as follows:

// Source file: src/class_persons.js

class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}

// initials() method snipped out...

fullName() {
return `${this.first} ${this.last}`;
}

get lastFirst() {
return `${this.last}, ${this.first}`;
}

// see below...
}

With this definition, you could access a .lastFirst property as if it actually were an attribute of the object; no parentheses are needed:

pp = new Person("Jean", "Dupont");
console.log(pp.fullName()); // "Jean Dupont"
console.log(pp.lastFirst); // "Dupont, Jean"

You can complement a getter with a setter, and it will perform any operations you want it to. For example, we may want let the user assign a value to .lastFirst and then change .first and .last appropriately.

Working somewhat cavalierly (no checks on arguments!), we could add the following definition to our Person class:

// Source file: src/class_persons.js

class Person {
// ...continued from above

set lastFirst(lf) {
// very unsafe; no checks!
const parts = lf.split(",");
this.last = parts[0];
this.first = parts[1];
}
}

pp.lastFirst = "Svensson, Sven";
console.log(pp); // Person {first: " Sven", last: "Svensson"}

Of course, having a property and having a getter or a setter for the same property is not allowed. Also, getter functions cannot have parameters, and setter functions must have exactly one.

The previous sections do not exhaust all of the possibilities of JS as to classes and objects (not by a long shot!), but I opted to go over the most likely ones for clarity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset