Reputation: 841
I have this code, which is kinda long winded but gets there in the end …
class WorksButLongWinded {
constructor (callback, params = {}) {
// defaults ...
this.foo = "string";
this.bar = 200;
this.callback = callback;
// params ...
if( typeof params.foo != "undefined" ) { this.foo = params.foo }
if( typeof params.bar != "undefined" ) { this.bar = params.bar }
}
}
I thought I might try using destructuring to speed things along, like this:
class DoesNotWork {
constructor (callback, params = {}) {
{
this.foo = "string",
this.bar = 200
} = params;
this.callback = callback;
}
}
... except that doesn't work. It doesn't even pass syntax muster.
What is a clean and simple way of writing a class constructor that takes an optional params
object with various optional parameters that override some default values?
Upvotes: 0
Views: 46
Reputation: 94299
You mean something like this?
class WorksButLongWinded {
constructor(callback, params) {
let defaults = {
foo: "string",
bar: 200
};
this.callback = callback;
Object.assign(this, defaults, params);
}
}
let a = new WorksButLongWinded(() => {});
console.log(a.foo); // "string"
console.log(a.bar); // "200"
let b = new WorksButLongWinded(() => {}, {foo: "bar"});
console.log(b.foo); // "bar"
console.log(b.bar); // "200"
Object.assign
does exactly what you want.
Upvotes: 2
Reputation: 2646
I think the way you are destructuring is incorrect. Try the below code where we destructure from params and then assign the values to this.
class WorksButLongWinded {
constructor (callback, params = {}) {
const {foo = "string", bar = 200} = params;
this.foo = foo;
this.bar = bar;
this.callback = callback;
}
}
Upvotes: 1