Why parentheses (grouping operator) aren't needed to call a “get method” through an instance?

孤人 提交于 2019-12-11 17:34:17

问题


I am reading about JavaScript Classes at MDN reference, and see an example where a method is defined using a get keyword. Here, I noticed that no parentheses (grouping operator ()) are required to call such a method (defined using get keyword) through an instance of the class.

Like, in following example,

  • square.area syntax calls the Rectangle Class's area method.
  • However, square.area() throws an error Uncaught TypeError: square.area is not a function.

Can someone please explain what am I missing here?

Here is the example:

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
console.log(square.area()); // Uncaught TypeError: square.area is not a function

回答1:


The grouping operator is used to change the evaluation order in calculations, e.g.

  (a + b) * c

parens that follow an identifier however like in your case aren't a grouping operator, they are a function call. You can only call functions and constructors though, not getters, which act like regular properties to the outside.



来源:https://stackoverflow.com/questions/57552992/why-parentheses-grouping-operator-arent-needed-to-call-a-get-method-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!