Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

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
...