Getters and Setters


Example 1

var person = {
    firstName: "John",
    lastName : "Doe",
    fullName : function() {
        return this.firstName + " " + this.lastName;
    }
};
// Display data from the object using a method:document.getElementById("demo").innerHTML = person.fullName();

Example 2

var person = {
    firstName: "John",
    lastName : "Doe",
    get fullName() {
        return this.firstName + " " + this.lastName;
    }
};
// Display data from the object using a getter:document.getElementById("demo").innerHTML = person.fullName;
Example 1 access fullName as a function: person.fullName().
Example 2 access fullName as a property: person.fullName.
The second example provides simpler syntax.


Why Using Getters and Setters?

  • It gives simpler syntax
  • It allows equal syntax for properties and methods
  • It can secure better data quality
  • It is useful for doing things behind-the-scenes

A Counter Example

Example

var obj = {
    counter : 0,
    get reset() {
      this.counter = 0;
    },
    get increment() {
      this.counter++;
    },
    get decrement() {
      this.counter--;
    },
    set add(value) {
      this.counter += value;
    },
    set subtract(value) {
      this.counter -= value;
    }
};
// Play with the counter:obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

Comments

Popular Posts