Why parentheses (grouping operator) aren't nee

2019-08-28 01:55发布

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条回答
聊天终结者
2楼-- · 2019-08-28 02:42

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.

查看更多
登录 后发表回答