问题
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.areasyntax calls theRectangleClass'sareamethod.- 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
回答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