Getters of imaginary properties in OOP in JavaScript
Accessors can be used to create imaginary properties that the object does not actually have. Let's look at an example. Let's say we have a class with two public properties:
class User {
constructor(name, surn) {
this.name = name;
this.surn = surn;
}
}
Let's make a third property that will contain the first and last name. Let's create an accessor property for this:
class User {
constructor(name, surn) {
this.name = name;
this.surn = surn;
}
get full() {
return this.name + ' ' + this.surn;
}
}
Let's check. Let's create a class object, passing the first and last name as parameters:
let user = new User('john', 'smit');
Let's output the values of public properties:
console.log(user.name); // 'john'
console.log(user.surn); // 'smit'
Now let's derive the value of our imaginary property:
console.log(user.full); // 'john smit'