Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what are ES6 class getter and setter actually?

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?

like image 641
feiyuerenhai Avatar asked Jan 07 '17 05:01

feiyuerenhai


People also ask

What are classes What are getters and setters?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

What is the purpose of getters and setters in JavaScript?

Getters and setters allow you to define Object Accessors (Computed Properties).

What is getter and setter properties?

What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.


1 Answers

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.

like image 58
Tiago Marinho Avatar answered Oct 14 '22 09:10

Tiago Marinho