Using a JS class, I would like to setup the class defaults using the constructor:
class Foo {
constructor(options = {}) {
this.options = options;
}
doSomething() => {
return `${this.options.sound} says ${this.options.animal}`;
}
}
Usage:
const foo = new Foo({
sound: 'moo',
animal: 'cow',
});
console.log(foo.doSomething());
// moo says cow
Now, let’s say later I want to use foo
object again, but update it’s options … For example:
// Let’s pretend `doSomething` has code to update the object’s options:
foo.doSomething({
sound: 'ribbit',
animal: 'frog',
});
// ribbit says frog
I am finding that I go back and forth on this; either I new
the object again
and create new instance with new options, or I re-use the same object and
write a class method to update options (like the pseudo-example immediately above).
Reasons for asking this question:
- I don’t really like creating new objects for utility-like modules (it just seems
wasteful to instantiate a whole new object just to modify options). - On the other hand, it seems not very clean to update the
options
of
a new class after it’s been initialized (potentially error-prone).
My questions:
- Is it best to just use
new Foo(<new options>)
again and create multiple instances? - Or, should I write a class method that update’s the current instance of
Foo
’s options?
Is there an ES6+ contemporary class-based pattern I can use to update options without creating a new instance? Or, should I just not worry about it and create new instances as needed?
I guess I’m curious what best practice might be in this situation?
I hope that makes some sense … Thanks in advance for reading and for the help!