Tuesday, July 14, 2015

ECMAScript 5 Object's Property Setters and Getters

Property Getters and Setters Methods

JavaScript objects have data properties and accessor properties:

  • a data property is a name and a value
  • an accessor property is a method or a pair of methods, known as getter and a setter

How JavaScript programs use accessor properties

  • if a program queries an accessor property the getter method is invoked
  • if a program sets an accessor property the setter method is invoked

How to define an accessor properties with object literals

  • two function declarations where the function keyword is replaced by get or set
  • the function names are the same as the property name
// definition of a read-write accessor property named 'propName'
var object = {   
   get propName() { /* getter method body */ },
   set propName(value) { /* setter method body */ }
};