I'm writing a small JS application and wanted to ask about some best practices. So, say I have a class called Dog
like this:
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log(`Bark Bark - ${this.name}`);
}
sayName() {
console.log(`My name is ${this.name}`);
}
}
When I create a new object that is an instance of the Dog
class, I always need to call bark()
and sayName()
. When doing this, is it advised to call these methods from the constructor like this:
constructor(name) {
this.name = name;
this.bark();
this.sayName();
}
or is it better to call them outside after initializing the object like this:
let germanShepard = new Dog("german shepard");
germanShepard.bark();
germanShepard.sayName();
Note: I never need to use bark()
and sayName()
after doing this. It's only a one time thing.
So, what do you guys recommend? Are there any advantages for one over the other? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire