簡體   English   中英

為什么通過實例調用“ get方法”不需要括號(分組運算符)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM