0

I want to understand why do we use getters and setters in javascript? When should it be used.

I know the general concept of getters and setters.

For example:

    var obj = new Object();
    obj['abc'] = "something"; //setting an object.
    console.log(obj['abc']); //getting

If a similar mechanism is achieved using the above code, when do we need to use getters and setters?

Can someone explain?

TechnoCorner
  • 4,879
  • 10
  • 43
  • 81
  • I'd recommend reading the MDN docs on Javascript Objects. It should go over a number of common use cases such as yours: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – Alex Johnson Jun 06 '16 at 18:44
  • 1
    Possible duplicate of [Javascript getters and setters for dummies?](http://stackoverflow.com/questions/812961/javascript-getters-and-setters-for-dummies) – But I'm Not A Wrapper Class Jun 06 '16 at 18:48
  • Getters and setters are recomended in JavaScript when using Class notation (syntaxic sugar). Getters and setters are public methods for reading and writing private properties. Hence, if you don't emulate private members there's no need to implement getters and setters. – kevin ternet Jun 06 '16 at 19:18

0 Answers0