Opt
0
Q:

javascript class getter setter

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  get cnam() {
    return this.carname;
  }
  set cnam(x) {
    this.carname = x;
  }
}

mycar = new Car("Ford");

document.getElementById("demo").innerHTML = mycar.cnam; //"Ford"
2
// *** JS Class GETTER / SETTER (+split)

	class Person {
        constructor(firstname, lastname) {
            this.firstname = firstname;
            this.lastname = lastname;
        }
        // getters => access properties
        // setters => change or mutate them
        get fullName() {
            return `Hello ${this.firstname} ${this.lastname}`;
        }
        set fullName(space) {
            const parts = space.split(' ');
            this.firstname = parts[0];
            this.lastname = parts[1];
        }
    }
    let run = document.getElementById("run");
    run.addEventListener('click', () => {
        let john = new Person('John', 'Connor');
        console.log(john.fullName);
        john.fullName = 'Billy Butcher';
        console.log(john.firstname + ' ' + john.lastname);
      	//console.log(`${john.firstname} ${john.lastname}`); same output
      // => has to be john.firstname otherwise undefined 
    }) 
// output => Hello John Connor | Billy Butcher
1
const language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}

language.current = 'EN';
language.current = 'FA';

console.log(language.log);
0

New to Communities?

Join the community