在类中的函数之前,"get"关键字是什么?

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)

  • get/set关键字是语法糖 - 因为对Polygon.calcArea()的调用也会充当getter吗? (7认同)
  • 你能不能只打电话给'p.calcArea`?如果没有,为什么不呢? (3认同)
  • 类是隐含在严格模式btw.http://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code (2认同)
  • @KitSunde - 至少在我的浏览器(Chrome,Win7)上,如果没有该声明,我会收到控制台错误而不是工作示例。这不是“答案”的一部分,就像“运行代码片段”按钮不是。 (2认同)

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 fullname
Run Code Online (Sandbox Code Playgroud)

  • 我想我可以进一步简化它。使用“ get”,您可以将类方法视为对象中的简单属性。如果不使用“ get”,您仍然可以通过调用.area()而不是.area来访问值。 (3认同)
  • 竖起大拇指的实际例子! (2认同)

Pra*_*man 18

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

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


Nim*_*yan 6

或更简单的方法,它只需键入函数名即可调用函数而无需用户“()”

以上两个函数同等关注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)