⊗jsOpAdVPS 52 of 60 menu

Mock Property Setters in OOP in JavaScript

In addition to getters of imaginary properties, you can also create their setters. In this case, inside the setter we must receive data, split it and write the corresponding parts to the necessary public properties.

Let's try it. Let's implement a setter for the imaginary property full:

class User { constructor(name, surn) { this.name = name; this.surn = surn; } get full() { return this.name + ' ' + this.surn; } set full(full) { let [name, surn] = full.split(' '); this.name = name; this.surn = surn; } }

Let's simplify the destructuring:

class User { constructor(name, surn) { this.name = name; this.surn = surn; } get full() { return this.name + ' ' + this.surn; } set full(full) { [this.name, this.surn] = full.split(' '); } }

Let's create an object of the class:

let user = new User('john', 'smit');

Let's write the data into our imaginary setter:

user.full = 'eric jons';

Let's check that the object's properties have changed:

console.log(user.name); // 'eric' console.log(user.surn); // 'jons' console.log(user.full); // 'eric jons'
uzfruzlitcs