什么是ES6类getter和setter呢? [英] what are ES6 class getter and setter actually?

查看:286
本文介绍了什么是ES6类getter和setter呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6类定义中实际的getter和setter方法是什么?他们是原型道具吗? for examle:

what are actually getter and setter methods in ES6 class definition? are they infact prototype props ? for examle:

class Person{
  constructor(){};
  get name(){
    return 'jack';
  }
  set name(){
    // ???
  }
}

这是否等于Person.prototype.name ='杰克';

does this equals to Person.prototype.name = 'jack';

另一个问题,我看过使用实例的道具的setter的例子:

and another question, i ve seen examples of setters which utilizes the instance's prop like:

class Person{
  constructor(){
    this._name = 'jack';
  };
  get name(){
    return this._name;
  }
  set name(val){
    this._name = val;
  }
}

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

i dont wanna do this way, i want something like:

class Person{
  constructor(){};
  get name(){
    return 'jack';
  }
  set name(val){
    // like this
    // name = val;
  }
}

可以做些什么?

推荐答案

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

Yes, it can be done: Just drop the setter/getter syntax and add a property to the class during initialization instead:

class Person{
    constructor(name){
        this.name = name;
    }
}

必须使用的属性的getter / setter语法根据其他属性计算,例如来自给定半径的圆圈的区域属性:

The getter/setter syntax exists for properties that must be calculated based on other properties, like the area property from a circle of a given 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);
    }
}

或者获取<$ c $的全名c> Person 具有 firstName lastName 属性的对象。你明白了。

Or getting the full name of a Person object with firstName and lastName properties. You get the idea.

这篇关于什么是ES6类getter和setter呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆