Naming the Root Object in ES6 Destructuring Function Parameters
ES6 offers destructuring as a concise way to extract properties from objects and arrays into variables. However, it can become challenging to retain the name of the root object when destructuring function arguments.
ES5 Inheritance Metaphor
In ES5, you could pass the entire options object "up" the inheritance chain to a parent class, allowing it to access all parameters:
// ES5: var setupParentClass5 = function(options) { textEditor.setup(options.rows, options.columns); }; var setupChildClass5 = function(options) { rangeSlider.setup(options.minVal, options.maxVal); setupParentClass5(options); // pass the options object UP };
ES6 Destructuring
With ES6 destructuring, extracting specific parameters becomes more convenient:
// ES6: var setupParentClass6 = ({rows, columns}) => { textEditor.setup(rows, columns); }; var setupChildClass6 = ({minVal, maxVal}) => { rangeSlider.setup(minVal, maxVal); setupParentClass6( /* ??? */ ); // how to pass the root options object? };
Options: Individual Extraction or Root Object Passing
One option is to extract each option individually in setupChildClass6(), and then pass them to setupParentClass6(). However, this approach can become verbose with many parameters:
// ugh. var setupChildClass6b = ({minVal, maxVal, rows, columns}) => { rangeSlider.setup(minVal, maxVal); setupParentClass6({rows, columns}); };
Using a Temporary Variable
A more concise solution is to use a temporary variable to hold the root options object before passing it to setupParentClass6():
const setupChildClass6 = options => { const {minVal, maxVal} = options; rangeSlider.setup(minVal, maxVal); setupParentClass6(options); };
This method allows you to destructure the specific parameters needed in setupChildClass6(), while still passing the entire options object to setupParentClass6().
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3