Javascript 类中函数前的“get”关键字是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31999259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:29:10  来源:igfitidea点击:

What is the "get" keyword before a function in a class?

javascriptmethodsgetter

提问by Matthew Harwood

What does getmean in this ES6 class? How do I reference this function? How should I use it?

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

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

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

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

回答by Amit

It means the function is a getter for a property.

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

To use it, just use it's name as you would any other property:

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

'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);

回答by Willem van der Veen

Summary:

概括:

The getkeyword will bind an object property to a function. When this property is looked up now the getter function is called. The return value of the getter function then determines which property is returned.

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

Example:

例子:

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

回答by Praveen Kumar Purushothaman

It is getter, same as Objects and Classes in OO JavaScript. From the MDN Docs for get:

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

The getsyntax binds an object property to a function that will be called when that property is looked up.

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