What actually is the getter and setter class of the ES6 class?

What are getter and setter methods in ES6 class definition? Are they a prototype prototype? for reference:

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

this corresponds to Person.prototype.name = 'jack';

and another question, I saw examples of setters that use a prop instance, for example:

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

I do not want to do this, I need something like:

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

what can be done?

+6
source share
2 answers

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

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

The syntax getter / setter exists for properties that should be calculated based on other properties, such as 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 get the full name of the Person object with firstName and lastName properties. You get the idea.

+9
source

According to MDN, the get syntax associates an object property with a function that will be called when that property is searched.

Here you return only the string "jack", it is not required for any property.

Interestingly, console.log (Person.prototype.name) log file

But Person.hasOwnProperty (name) registers false

also after creating an instance of the call to Person ie const x = new Person ();

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

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

+2
source

Source: https://habr.com/ru/post/1013854/


All Articles