[英]Why parentheses (grouping operator) aren't needed to call a “get method” through an instance?
我正在MDN參考上閱讀有關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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.