How to use get (getter) property to get the value of a local variable of an object in JavaScript

1 Answer

0 votes
class Worker {
    constructor(id, _name, _age) {
        this.id = id;
        let name = _name;
        let age = _age;
        this.show = function () {
            console.log(this.id + ' ' + name + ' ' + age);
        };
        Object.defineProperty(this, 'WName', {
            get: function() {
                return name;
            }
        });
    }
}
   
const worker = new Worker(2345, 'Tom', 54);
 
worker.show();
 
console.log(worker.id);
 
console.log(worker.name);
 
console.log(worker.WName)
 
worker.WName = 'abc';
worker.show();

     
/*
run:
   
2345 Tom 54
2345
undefined
Tom
2345 Tom 54
 
*/

 



answered Mar 6, 2020 by avibootz
edited Mar 6, 2020 by avibootz
...