Explain Calling And Setting Getters And Setters Like I'm Five

Alex Gwartney - Jan 8 '18 - - Dev Community

Could someone explain to me in detail as to why we can do these two specific things with the get and set methods?

So I understand how to define the get and set methods. What I am confused at is why we don't invoke them like normal methods? For instance, as you see in the examples below given from the mdn docs. They call the set method by defining it as an object property with a value?

javascript language.current = 'EN';

And then when we are calling the get method we end up calling the method again as if it was a property on the object instead of invoking a method on the object?

javascript language.log

Hopefully this makes sense it was just something iam not quite grasping the concept of what is happening.

var obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    if (this.log.length == 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
}

var language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}

language.current = 'EN';

console.log(language.log);

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .