4 ms·
I've never seen this pattern before in JS, in the parameters for the constructor. playing with it in the browser, I can see it lets you define default values fo
by nkrisc 7y ago
I've never seen this pattern before in JS, in the parameters for the constructor. playing with it in the browser, I can see it lets you define default values for expected arguments when calling it but you can provide other values.
What is this called? I'd like to read more about it.
class Resource{
constructor({
min = 0,
max = 1,
count = 0
}={}){
this.min = min;
this.max = max;
this.count = count;
}
}
- chiyc 7y agoI think I would call it nested destructuring with default values.
- nkrisc 7y agoDestructuring, that rings a bell. Thank you.
- capableweb 7y agoYeah, the trick is basically many things chained together. First is to pass a object to a function instead of position-locked arguments. Second is to default to a empty object. Third is to destruct the object in the function parameter directly. Fourth to supply default destruct values. Fifth is to set the values in the current instance of that class.
- deleted 7y ago[deleted]
- orisa2 7y agoFrom the post, I wasn't sure if you knew, but JS also has regular default parameters if that's all you want.
- capableweb 7y agoNot as nice though, as the arguments still depend on the order. Passing a object gives the benefit of named arguments AND position of the arguments no longer matter (as object keys don't have order and also, it's a object with key/values)
- lxe 7y agoDestructuring parameters with default values. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...