ES6 - Use getters and setters to Control Access to an Object

I’m looking into submitting a pull request for answers people find useful. You can’t really fault FCC devs. They have to code the site on their free time. Whereas I have more time to troubleshoot people’s questions.

Considering even commercial software has issues with documentation, I feel they’re doing great imho. And that’s why this forum is helpful.

I think I may have confused you because I made a critical mistake, which I just went back to fix. The example should have looked like this

class SomeClass {
  constructor() {
      this.value = 'my initial value'
  }

  get value() {
      return this.value
  }

  set value(val) {
      this.value = val
   }
}

The reason we use get and set is so that we can work with a class like a regular object. Variables inside a class are private data, and only the class’ methods can access that data.

So internally the js engine knows that

  • when you try to set the property to a value, it will run set someFunc.
  • when you try to get the value of the property, it will run get someFunc.

This allows you to be in absolute control of how to set the data, and what data gets returned to the caller.

For instance, suppose I have a class to create a bank account. In order to make accounting easier, the specs require us to save the total as one cent denominations, but can only accept dollars.

Why? Because sometimes specs are specs and the client is boss. :confused: lol

For the sake of this example, let’s assume you cannot set the beginning total in the contructor.

class BankAccount {
  constructor() {
      this.total = 0
  }

  get total() {
    // get the total in dollars
      return this.total / 100
  }

  set total(amt) {
  // convert amt to 1 cent denominations and deposit
      this.total = amt * 100
   }
}

Now when I create a new Bank account for someone, I can treat that specific property like it was an object literal.

// create a new account for Bob
const bobsAcct = new BankAccount()

// make sure bob's account starts at 0
// this "get"s the data
console.log(bobsAcct.total) // 0

// set his opening balance to $100
// this "set"s the data
bobsAcct.total = 100

// now let's see how much he has
console.log(bobsAcct.total) // 100

By using setters and getters, we were able to use the class like an object literal.

We also abstracted the dollar → penny conversion, so the user of the class doesn’t have to worry about that logic.

I think that’s what you were asking for. So if I misunderstood, let me know what to clarify.

6 Likes