我正在 MDN reference 阅读有关 JavaScript 类的内容,并查看使用 get
关键字定义方法的示例。在这里,我注意到通过类的实例调用此类方法(使用 get
关键字定义)不需要括号(分组运算符 ()
)。
就像下面的例子一样,
square.area
语法调用Rectangle
类的area
方法。- 但是,
square.area()
会抛出错误Uncaught TypeError: square.area is not a function
。
有人可以解释一下我在这里缺少什么吗?
示例如下:
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
最佳答案
分组运算符用于更改计算中的求值顺序,例如
(a + b) * c
标识符后面的括号,但就像您的情况一样,不是分组运算符,而是函数调用。不过,您只能调用函数和构造函数,而不能调用 getter,它们对外部的作用就像常规属性一样。
关于javascript - 为什么通过实例调用 "get method"不需要括号(分组运算符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57552992/