【问题标题】:What is the "get" keyword before a function in a class?什么是类中函数前的“get”关键字?
【发布时间】:2022-01-18 04:22:23
【问题描述】:

get 在这个 ES6 类中是什么意思?我如何引用这个函数?我应该如何使用它?

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea()
  }

  calcArea() {
    return this.height * this.width;
  }
}

【问题讨论】:

  • 它很可能只是一个getter,但在一个类而不是一个对象中。它并不是真正的 ES6 特定的。
  • @Xufox 你的意思是它不是 ES6 特定的?
  • @KeithNicholas:它在 ES5 中也一样。
  • @KeithNicholas Getters 自 ES5 以来就存在,我认为。这里唯一的 ES6 是 class 语法,但 getter 并不是什么新鲜事。

标签: javascript methods getter


【解决方案1】:

这意味着该函数是一个属性的getter。

要使用它,只需像使用任何其他属性一样使用它的名称:

'use strict'
class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea()
  }

  calcArea() {
    return this.height * this.width;
  }
}

var p = new Polygon(10, 20);

alert(p.area);

【讨论】:

  • @KitSunde - 至少在我的浏览器(Chrome、Win7)上,如果没有该语句,我会收到控制台错误而不是工作示例。这不是“答案”的一部分,就像“运行代码 sn-p”按钮不是一样。
  • 你不能直接打电话给p. calcArea吗?如果没有,为什么不呢?
  • get / set 关键字只是语法糖吗?因为对 Polygon.calcArea() 的调用也可以作为 getter 吗?
  • so函数获取get关键字不能有参数?
【解决方案2】:

总结:

get 关键字将对象属性绑定到函数。现在查找此属性时,将调用 getter 函数。然后 getter 函数的返回值决定返回哪个属性。

示例:

const person = {
    firstName: 'Willem',
    lastName: 'Veen',
    get fullName() {
        return `${this.firstName} ${this.lastName}`;
    }

}

console.log(person.fullName);
// When the fullname property gets looked up
// the getter function gets executed and its
// returned value will be the value of fullname

【讨论】:

  • 为实际示例点赞!
  • 我想我可以进一步简化它。 'get' 让您可以将类方法视为对象中的一个简单属性。如果您不使用“get”,您仍然可以通过调用 .area() 而不仅仅是 .area 来访问该值
【解决方案3】:

它是getter,与OO JavaScript中的对象和类相同。来自 get 的 MDN 文档:

get 语法将对象属性绑定到将在查找该属性时调用的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2021-08-18
    • 1970-01-01
    • 2014-08-05
    相关资源
    最近更新 更多