Throughout the entirety of the JavaScript course (part 2), Mosh always supplies an argument when creating a constructor in a class. Is there a way for me to not have to list the argument in the constructor but still be able to use it? I don’t want to have to supply a value when instantiating my class, especially if I don’t know what value I need. For example take this code:
class Foo{
constructor(foo, bar, x, y, z) {
this.foo = foo;
this.bar = bar;
this.x = x;
this.y = y;
this.z = z;
}
spew() {
console.log(this.foo + ' ' + this.bar + ' ' + this.x + ' ' + this.y + ' ' + this.z);
}
}
const f = new Foo('value');
f.spew();
What if I want to have the ‘value’ refer to x in this case (instead of foo by default)?
My implementation is to list all values in the constructor but the ones I will be setting on the instance are listed first. For example, if I want to use x, z, and foo, on the instance it looks like this:
class Foo{
constructor(x, z, foo, bar, y) {
this.foo = foo;
this.bar = bar;
this.x = x;
this.y = y;
this.z = z;
}
spew() {
console.log(this.foo + ' ' + this.bar + ' ' + this.x + ' ' + this.y + ' ' + this.z);
}
}
const f = new Foo('xValue', 'zValue', 'fooValue');
f.spew();
This feels clunky and improper. Is there a better/cleaner way to do this?