Getters & Setters

Getters & Setters

  • Getters and Setters allow developers to write methods that enable reading (get) and the writing (set) of properties of the instances (objects)

  • Getters and setters is a common pattern used in object oriented programming; ES6 classes introduced a new syntax for getters and setters on object properties

  class Car {
    constructor(make, model) {
      this._make = make
      this._model = model
    }

    get make() {
      return this._make
    }

    get model() {
      return this._model
    }

    set model(newModel) {
      this._model = newModel
    }
  }

  const myTesla = new Car("Telsa", "Model 3")
  console.log(myTesla.make)
  console.log(myTesla.model)

  // change model of myTesla
  myTesla.model = "Model X"
  console.log(myTesla.model)
  

Here’s a summary of the code above:

  • We are using get and set which allows us to run code on the reading or writing of a property

  • Notice that we’ve prepended our property names with underscores (_make and _model) this is a convention to indicate that these properties should not be accessed directly

  • Our getters simply return the value associated with the property, for example:

        get make() {
          return this._make
        }
        
    
  • Our setters allows use to reassign a new value to our properties, for example:

        set model(newModel) {
          this._model = newModel
        }
        
    
  • We call out getter methods the using dot notation *without parentheses

    myTesla.make // this returns the make property
    
  • We call out setter methods the using dot notation reassigning a new value using an = sign

    myTesla.model = "Model X" // this sets the model property to new value
    

Example

JS Bin on jsbin.com


Why Getters and Setters?

  • Getters and Setters effectively protect your data, particularly when creating classes

  • They provide a simple syntax for reading and writing properties


Exercise

  • In the Employee constructor, prepend the name and salary properties with an underscore (_).

  • Add a getter method called name() that returns the value of the name property

  • Add a getter method called salary() that returns the value of the salary property

  • Add a setter method called name(newName) that allows you to provide an employee with a new name

class Employee {
  constructor(name, salary) {
    this.name = name
    this.salary = salary
  }

  // add code below


  // add code above
}

/*
  Uncomment lines below after you've made your updates
*/

// const methodMan = new Employee("Johnny Blaze", "100000")
// console.log(methodMan.name)
// console.log(methodMan.salary)
// methodMan.name = "Jonathan Blaze"
// console.log(methodName.name)

JS Bin on jsbin.com