class 中函数前的 "get" 关键字是什么?
What is the "get" keyword before a function in a class?
ES6 class中的get
是什么意思?我如何引用这个函数?我应该如何使用它?
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea()
}
calcArea() {
return this.height * this.width;
}
}
表示函数是getter for a 属性.
要使用它,只需像使用任何其他名称一样使用它的名称 属性:
'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);
它是getter,与Objects和OO JavaScript中的类相同。来自 get
的 MDN 文档:
The get
syntax binds an object property to a function that will be called when that property is looked up.
总结:
get
关键字将对象 属性 绑定到函数。现在查找 属性 时,调用 getter 函数。 getter 函数的 return 值然后确定哪个 属性 是 returned。
示例:
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
ES6 class中的get
是什么意思?我如何引用这个函数?我应该如何使用它?
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea()
}
calcArea() {
return this.height * this.width;
}
}
表示函数是getter for a 属性.
要使用它,只需像使用任何其他名称一样使用它的名称 属性:
'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);
它是getter,与Objects和OO JavaScript中的类相同。来自 get
的 MDN 文档:
The
get
syntax binds an object property to a function that will be called when that property is looked up.
总结:
get
关键字将对象 属性 绑定到函数。现在查找 属性 时,调用 getter 函数。 getter 函数的 return 值然后确定哪个 属性 是 returned。
示例:
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