为什么不需要括号(分组运算符)来调用"get方法"?通过实例? [英] Why parentheses (grouping operator) aren't needed to call a "get method" through an instance?
问题描述
我正在 MDN参考中阅读有关JavaScript类的信息,并查看一个使用get
关键字定义方法的示例.在这里,我注意到通过类的实例调用这种方法(使用get
关键字定义)不需要括号(分组运算符()
).
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.
例如,在下面的示例中
-
square.area
语法调用Rectangle
类的area
方法. - 但是,
square.area()
会引发错误Uncaught TypeError: square.area is not a function
.
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?
以下是示例:
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.
(a + b) * c
跟在标识符后面的
括号不是您的分组运算符,而是函数调用.不过,您只能调用函数和构造函数,而不能调用类似于外部常规属性的getter.
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.
这篇关于为什么不需要括号(分组运算符)来调用"get方法"?通过实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!