1

I want to convert Mike Herchel's Importing CSS Breakpoints into ES6 class. For this, I chose to use get and set to finally learn how to.

My code so far:

export default class Breakpoints {
  constructor() {
    this.value = null;

    this.refreshValue();

    window.addEventListener('resize', () => {
      this.refreshValue();
    });
  }

  refreshValue() {
    let val = window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/\"/g, '');

    this.value = val;
  }

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

  get value() {
    return this.value;
  }
}

Problem is, when I run it, I am getting Maximum call stack size exceeded. Where I did go wrong?

j08691
  • 204,283
  • 31
  • 260
  • 272
Tomek Buszewski
  • 7,659
  • 14
  • 67
  • 112
  • Not sure why the answer was deleted, but it was correct - your get/set is hiding the `this.value` reference and your getter is calling itself over and over – CodingIntrigue May 05 '16 at 13:40
  • @RGraham the fundamental part of the answer (the recursive call to the getter) was correct, but the proposed fix was completely wrong – Alnitak May 05 '16 at 13:41
  • @Alnitak I was expecting it to be edited though. Seemed trivial to just remove `private _value` – CodingIntrigue May 05 '16 at 13:43
  • 2
    yeah, trivial enough, except that there's not much point having a getter/setter that just mirrors an exposed property (even if it is prefixed) – Alnitak May 05 '16 at 13:44

1 Answers1

4

There's absolutely no reason to use getters/setters here, they don't do anything else than a normal property would do.

When I run it, I am getting Maximum call stack size exceeded. Where I did go wrong?

Your getter returns the value of the property again, thereby invoking itself. Your settter sets the value of the property again, thereby invoking itself. Don't do that.

If you really wanted to use getters for some reason, go for

export default class Breakpoints {
  constructor() {
    this._val = null;

    this.refreshValue();
    window.addEventListener('resize', () => {
      this.refreshValue();
    });
  }

  refreshValue() {
    this._val = window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/\"/g, '');
  }

  get value() {
    return this._val;
  }
  // no `value` setter, because it can't be changed from outside
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375