为什么不需要括号(分组运算符)来调用"get方法"?通过实例? [英] Why parentheses (grouping operator) aren't needed to call a "get method" through an instance?

查看:101
本文介绍了为什么不需要括号(分组运算符)来调用"get方法"?通过实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 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 the Rectangle Class's area method.
  • However, square.area() throws an error Uncaught 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆