What are get and set methods in ES6 class definition? Are they in fact prototype properties? For example:
class Person{
constructor(){};
get name(){
return 'jack';
}
set name(){
// ???
}
}
Does this equal to Person.prototype.name = 'jack'? Furthermore, I've seen examples of setters which utilize the instance's prop like:
class Person{
constructor(){
this._name = 'jack';
};
get name(){
return this._name;
}
set name(val){
this._name = val;
}
}
I don't want to do it this way; I want something like:
class Person{
constructor(){};
get name(){
return 'jack';
}
set name(val){
// like this
// name = val;
}
}
What can be done?
Yes, it can be done: Just drop the setter/getter syntax and add a property to the class during initialization instead:
The getter/setter syntax exists for properties that must be calculated based on other properties, like the
areaproperty from a circle of a givenradius:Or getting the full name of a
Personobject withfirstNameandlastNameproperties. You get the idea.