什么是ES6类getter和setter呢?

fei*_*hai 14 javascript setter ecmascript-6

什么是ES6类定义中的getter和setter方法?他们是原型道具吗?为了考试:

class Person{
  constructor(){};
  get name(){
    return 'jack';
  }
  set name(){
    // ???
  }
}
Run Code Online (Sandbox Code Playgroud)

这等于Person.prototype.name ='jack';

另一个问题,我已经看到了使用实例的prop的setter的例子:

class Person{
  constructor(){
    this._name = 'jack';
  };
  get name(){
    return this._name;
  }
  set name(val){
    this._name = val;
  }
}
Run Code Online (Sandbox Code Playgroud)

我不想这样做,我想要的东西:

class Person{
  constructor(){};
  get name(){
    return 'jack';
  }
  set name(val){
    // like this
    // name = val;
  }
}
Run Code Online (Sandbox Code Playgroud)

怎么办?

Tia*_*nho 20

是的,可以这样做:只需删除setter/getter语法并在初始化期间向类添加属性:

class Person{
    constructor(name){
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

getter/setter语法存在于必须基于其他属性计算的属性,例如area来自给定圆的属性radius:

class Circle {
    constructor (radius) {
        this.radius = radius;
    }
    get area () {
        return Math.PI * this.radius * this.radius;
    }
    set area (n) {
        this.radius = Math.sqrt(n / Math.PI);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者Person使用firstNamelastName属性获取对象的全名.你明白了.