Mat*_*ood 86 javascript methods getter
get这个ES6课程意味着什么?我该如何参考这个功能?我该怎么用?
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea()
}
calcArea() {
return this.height * this.width;
}
}
Run Code Online (Sandbox Code Playgroud)
Ami*_*mit 92
It means the function is a getter for a property.
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);Run Code Online (Sandbox Code Playgroud)
Wil*_*een 27
所述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 fullnameRun Code Online (Sandbox Code Playgroud)
或更简单的方法,它只需键入函数名即可调用函数而无需用户“()”
以上两个函数同等关注person.fullName()和person.fullName
const person = {
firstName: 'Willem',
lastName: 'Veen',
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
console.log(person.fullName());Run Code Online (Sandbox Code Playgroud)
const person = {
firstName: 'Willem',
lastName: 'Veen',
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
console.log(person.fullName);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25643 次 |
| 最近记录: |