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:

javascriptclass 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:

javascriptclass 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:

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

Let's write the data into our imaginary setter:

javascriptuser.full = 'eric jons';

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

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