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 theRectangle
Class'sarea
method.- However,
square.area()
throws an errorUncaught 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
The grouping operator is used to change the evaluation order in calculations, e.g.
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.