What is the "get" keyword before a function in a class?

Matthew Harwood picture Matthew Harwood · Aug 14, 2015 · Viewed 41.8k times · Source

What does get mean in this ES6 class? How do I reference this function? How should I use it?

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea()
  }

  calcArea() {
    return this.height * this.width;
  }
}

Answer

Amit picture Amit · Aug 14, 2015

It means the function is a getter for a property.

To use it, just use it's name as you would any other property:

'use strict'
class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea()
  }

  calcArea() {
    return this.height * this.width;
  }
}

var p = new Polygon(10, 20);

alert(p.area);