Javascript Set:Get Pointless?

Viewed 403

I have been experimenting with getters and setters with the following pattern:

var mytab = {
  _tab: undefined,
  get: function () {
    return this._tab;
  },
  set: function (tab) {
    this._tab = tab;
    return tab;
  }
}

My question is, given you have to access those methods explicitly, ie:

mytab.get();
mytab.set('thistab');

Why bother having get or set at all? Why not call them whatever you like? ie:

var mytab = {
  _tab: undefined,
  getthetab: function () {
    return this._tab;
  },
  setthetab: function (tab) {
    this._tab = tab;
    return tab;
  }
}

I may have missed some fundamental principle here, but both these objects behave exactly the same.

I assumed having special 'setters' and 'getters' would allow the object to be modified using it's object name, ie:

var a = mytab;
mytab = 'thistab';

Or even:

var a = mytab();
mytab() = 'thistab';

This is what I expected, and what I wanted, however those instructions give errors, namely that mytab() is not a function.

I would appreciate some clarity on what special significance the set and get object methods actually have.

2 Answers

The following use case can illustrate advantage of using getters and setters

var person = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};
console.log(person.fullName);

Using getter we could use get fullName as if it was a property of person without the need of maintaining separate field.

In your first example, you haven't declared getters/setters. You've created an object with two methods called get and set.

To declare getters/setters, you'll have to choose an arbitrary name, and prefix it with get or set, like:

var mytab = {
  _tab: undefined,
  get tab() {
    return this._tab;
  },
  set tab(tab) {
    this._tab = tab;
    return tab;
  }
}

In this case, they form a so-called accessor property, that has the chosen name:

console.log(mytab.get) //undefined
console.log(mytab.set) //undefined

mytab.tab = 'foo'
console.log(mytab._tab) //foo
mytab._tab = 'bar'
console.log(mytab.tab) //bar
console.log(Object.getOwnPropertyDescriptor(mytab, 'tab')) /*
{
  get: function(){...},
  set: function(tab){...},
  ...
}
*/

However, you cannot overload operators or otherwise define a single getter/setter pair for your objects, that would allow you to assign a value or read a value from the object itself.

You can only define getters/setters for the properties on the object.

So,

var a = mytab

or

mytab = a

cannot be intercepted, and doesn't do what you expect (the first assigns the object itself to another variable (a), while the second reassigns the variable mytab with the value of a without even affecting / interacting with the object).

Related