What is the “get” keyword before a function in a class?

前端 未结 4 1025
执念已碎
执念已碎 2020-12-13 03:02

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

class Polygon {
  constructor(height, width) {
           


        
4条回答
  •  感动是毒
    2020-12-13 03:44

    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);

提交回复
热议问题