0

I'm playing around with ES6 Class and i'm wondering what the point is of using the get or set method for properties on that class. They seem pointless b/c you can set any arbitrary property on the class anyways.

For example with this class

class Group {

  constructor() {}

  set name(newName) {
    this._name = newName;
  }

  get name() {
    return this._name;
  }

  print() {
    console.log('this._name = ', this._name);
    console.log('this.name = ', this.name);
  }
}

I get these results

var group = new Group();
group._name = 'foo';
console.log('_name = ', group._name); => _name = foo
console.log('name = ', group.name); => name = foo
group.print(); => this._name = foo
               => this.name = foo

var group2 = new Group();
group2.name = 'bar';
console.log('_name = ', group2._name); => _name = bar
console.log('name = ', group2.name); => name = bar
group2.print(); => this._name = bar
                => this.name = bar

With the results of this example, it seems that by using the new set and get method just adds unnecessary bloat to my class.

Catfish
  • 18,876
  • 54
  • 209
  • 353
  • 1
    Those methods are useful when you want to manipulate/modify the values before getting and setting them, if you don't want to do this, you don't need them. – Ram Dec 08 '15 at 14:35
  • If your getter and setter just read/write to another property and do nothing else, then they are indeed unnecessary. – Felix Kling Dec 08 '15 at 14:36

1 Answers1

1

Using the property accessors allows you to run additional code, for instance, checking the values are valid:

set name(newName) {
  if (newName === '')
      throw new Error("Name cannot be empty");
  this._name = newName;
}

Or computing complex properties:

get fullname() {
    return this.firstName + ' ' + this.lastName;
}
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • I can see your `set` example, but in your `get` example couldn't you just do away with the `get` and just have `fullname()...`? – Catfish Dec 08 '15 at 14:37
  • You could do, but then it's a method call rather than a property. I work in .NET a lot - it's very useful to have properties rather than methods sometimes. – James Thorpe Dec 08 '15 at 14:37
  • 1
    Oh gotcha b/c with the `get` you can just do `myGroup.fullname` rather than `myGroup.fullname()`. – Catfish Dec 08 '15 at 14:40