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
What is the "get" keyword before a function in a class?
提问by Matthew Harwood
What does get
mean 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 get
keyword 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