How to use get (getter) and set (setter) property in JavaScript ES6

1 Answer

0 votes
class Worker {
    constructor(id, name) {
        this.id = id;
        this.name = name;
    }
    get WName() {
        return this.name;
    }
    set WName(value) {
        this.name = value;
    }
    show() {
        console.log(this.id + ' ' + this.name);
    }

}
 
const w = new Worker(2345, 'Tom');
 
w.show();

console.log(w.WName);

w.WName = 'Emma';
w.show();

     
/*
run:
   
2345 Tom
Tom
2345 Emma
 
*/

 



answered Mar 6, 2020 by avibootz
...