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;
}
}
Not 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)
Yeah, 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.
Comments
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.
Destructuring parameters with default values.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
From the post, I wasn't sure if you knew, but JS also has regular default parameters if that's all you want.
Not 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)
I think I would call it nested destructuring with default values.
Destructuring, that rings a bell. Thank you.
Yeah, 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.