Assign properties in a constructor’s parameter object (with defaults) to object being instantiated in JavaScript
This is a little something I ended up playing around with this morning before figuring out how to do it (after spending far too much time down a rabbit hole with object destructuring when what I really needed was creative use of the spread operator).
(Useful for custom objects in JSDB 5 – https://codeberg.org/small-tech/jsdb#custom-data-types)
#JavaScript #parameterObject #defaults #JSDB
gists/assign-properties-in-a-constructors-parameter-object-with-defaults-to-object-being-instantiated-in-JavaScript.md at main
gists - A place for me to post and share small, self-contained code snippets.Codeberg.org
Zwifi
in reply to Aral Balkan • • •Aral Balkan
in reply to Zwifi • • •@Zwifi It’s because we’re creating a new object that initially contains the default properties and then copying over the actual properties from the parameter object.
The inline syntax is confusing to read, however, so I just updated the gist to separate it out into three statements. Also, given that the spread syntax is syntactic sugar for Object.assign() and since we’re using Object.assign() anyway, I added an example that only uses Object.assign(). Hopefully it’s easier to read now :)
Aral Balkan
in reply to Aral Balkan • • •@Zwifi Although… if you don’t need to reference `this` in your defaults, you can both simplify all that and get type inference for free by defining your defaults in class fields with initialisers.
(Updated the gist with an example of that: https://codeberg.org/aral/gists/src/branch/main/assign-properties-in-a-constructors-parameter-object-with-defaults-to-object-being-instantiated-in-JavaScript.md#so-is-all-this-really-necessary)
gists/assign-properties-in-a-constructors-parameter-object-with-defaults-to-object-being-instantiated-in-JavaScript.md at main
Codeberg.org