ES6 Destructuring Function Parameter: Preserving Root Object Name
In ES6, destructuring function arguments allows for concise and expressive parameter handling. However, when working with multiple configuration parameters spread across a parent-child class hierarchy, the name of the root object may be lost after destructuring.
In ES5, you can pass the root object up the hierarchy using inheritance:
// 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 };
However, in ES6 using destructuring, this becomes an issue:
// 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? };
To retain the root object's name, you can declare it as a parameter before destructuring:
const setupChildClass6 = options => { const {minVal, maxVal} = options; rangeSlider.setup(minVal, maxVal); setupParentClass6(options); };
Alternatively, you can extract all options individually in setupChildClass6:
var setupChildClass6b = ({minVal, maxVal, rows, columns}) => { rangeSlider.setup(minVal, maxVal); setupParentClass6({rows, columns}); };
However, this approach requires more lines of code and may not be optimal when dealing with multiple destructured variables.
The above is the detailed content of How to Preserve the Root Object Name When Destructuring Function Parameters in ES6?. For more information, please follow other related articles on the PHP Chinese website!