S
S
sad09902017-11-26 08:18:42
JavaScript
sad0990, 2017-11-26 08:18:42

What is the functional difference between constructor and set in JavaScript classes? Why should a class description contain both?

And what is _dogName for, if there is just dogName?

class Dog
{
  constructor(dogName)
  {
     this.dogName = dogName;
  }
  set dogName(value)
  {
    this._dogName = value;
  }
  get dogName()
  {
    return this._dogName;
  }
}
let dog = new Dog("Rex");
console.log(dog.dogName);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2017-11-26
@alexey-m-ukolov

Why should a class description contain both?
Why do you think so? There may be neither one nor the other.
What is the functional difference between constructor and set in JavaScript classes?
Setters are responsible for setting the value of one particular property; constructor - for the initialization of the object as a whole.
And what is _dogName for, if there is just dogName?
A property object (_dogName) and a setter method (dogName) cannot have the same name.
The example you gave can be simplified to this and everything will continue to work:
class Dog
{
  constructor(dogName)
  {
     this.dogName = dogName;
  }
}
let dog = new Dog("Rex");
console.log(dog.dogName);

Forget about getters and setters for now - when you need them, you will immediately understand why they are needed. Focus on constructors to start with.

A
Alex Ander, 2017-11-26
@loktionov129

And what is _dogName for, if there is just dogName?

Getters and setters - A classic of the genre. They are needed so that users of the class do not have full access to the internals of the Dog class. So that the class developer can control the setting of the value of dogName. For example:
const blackList = ['Мурзик', 'Васька', 'Эпифантий'];
// ... 
  set dogName(value)
  {
    if (!value || !_.isString(value)) {
      throw new Error('value must be a string!') ;
    }
    if (blackList.includes(value) {
      throw new Error('wrong value!') ;
    }
    this._dogName = value;
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question