0

Here is a JS class.

class Rectangle {
    constructor(height, width) {
      this.height = height;
      this.width = width;
    }
    // Getter
    get area() {
      return this.calcArea();
    }
    // Method
    calcArea() {
      return this.height * this.width;
    }
  }

  const square = new Rectangle(10, 10);

  console.log(square.area); // 100

It seems to work fine. However, I don't understand why we need to specify the get keyword for area() but not for calcArea() although both are returning values. Could someone explain this? And if possible, if someone could also explain this from react's perspective and whether this still applies for class components? Thanks.

Grateful
  • 9,685
  • 10
  • 45
  • 77
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get – sdgluck Feb 07 '20 at 09:41
  • 4
    The only real difference is that `area` will invoke and return the value when `.area` is *referenced*, whereas `calcArea` will only run when the function is explicitly invoked with `()`. – CertainPerformance Feb 07 '20 at 09:41
  • @CertainPerformance Okay, got it! But why would I ever need to reference a method like that, when I can simply invoke it? – Grateful Feb 07 '20 at 10:03
  • It can be used to hide implementation details. Sometimes you might like that, though IMO often you wouldn't, since it can make things a bit confusing. Eg `.innerHTML` is a getter/setter. – CertainPerformance Feb 07 '20 at 10:04

0 Answers0