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

前端 未结 4 1022
执念已碎
执念已碎 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:37

    or more simple way it just call the function without needing to user "()" just by typing the function name

    the two above function are equal attention to person.fullName() and person.fullName

    const person = {
        firstName: 'Willem',
        lastName: 'Veen',
        fullName() {
            return `${this.firstName} ${this.lastName}`;
        }
    
    }
    
    console.log(person.fullName());

    const person = {
        firstName: 'Willem',
        lastName: 'Veen',
        get fullName() {
            return `${this.firstName} ${this.lastName}`;
        }
    
    }
    
    console.log(person.fullName);

    0 讨论(0)
  • 2020-12-13 03:42

    Summary:

    The get keyword will bind an object property to a function. When this property is looked up now the getter function is called. The return value of the getter function then determines which property is returned.

    Example:

    const person = {
        firstName: 'Willem',
        lastName: 'Veen',
        get fullName() {
            return `${this.firstName} ${this.lastName}`;
        }
    
    }
    
    console.log(person.fullName);
    // When the fullname property gets looked up
    // the getter function gets executed and its
    // returned value will be the value of fullname

    0 讨论(0)
  • 2020-12-13 03:42

    It is getter, same as Objects and Classes in OO JavaScript. From the MDN Docs for get:

    The get syntax binds an object property to a function that will be called when that property is looked up.

    0 讨论(0)
  • 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);

    0 讨论(0)
提交回复
热议问题