what are ES6 class getter and setter actually?

安稳与你 提交于 2019-12-06 18:18:09

问题


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(){
    // ???
  }
}

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

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;
  }
}

what could be done?


回答1:


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;
    }
}

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);
    }
}

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




回答2:


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

Here you are returning just a string 'jack' it is not binding to any property.

Interestingly console.log(Person.prototype.name) logs jack

But Person.hasOwnProperty(name) logs false

also once we create instance of Person call i.e const x = new Person();

console.log(x.name) -> this throws error, cant read property x.name because x.hasOwnProperty(name) is false

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get



来源:https://stackoverflow.com/questions/41518139/what-are-es6-class-getter-and-setter-actually

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!