问题
Is there a way to retain the name of a destructured function argument? I.e., the name of the root object?
In ES5, I might do this (using inheritance as a metaphor to make the point):
// ES5:
var setupParentClass5 = function(options) {
textEditor.setup(options.rows, options.columns);
};
var setupChildClass5 = function(options) {
rangeSlider.setup(options.minVal, options.maxVal);
setupParentClass5(options); // <= we pass the options object UP
};
I'm using the same options
object to hold multiple configuration parameters. Some parameters are used by the parent class, and some are used by the subclass.
Is there a way to do this with destructured function arguments in ES6?
// 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?
};
Or do I need to extract all of the options in setupChildClass6()
so that they can be individually passed into setupParentClass6()
?
// ugh.
var setupChildClass6b = ({minVal, maxVal, rows, columns}) => {
rangeSlider.setup(minVal, maxVal);
setupParentClass6({rows, columns});
};
回答1:
I have the 'options' arguments on too many places myself. I would opt for 1 extra line of code. Not worthy in this example, but a good solution when having destructuring on more lines.
const setupChildClass6 = options => {
const {minVal, maxVal} = options;
rangeSlider.setup(minVal, maxVal);
setupParentClass6(options);
};
回答2:
You cannot do it directly in the arguments, but you can extract the values afterward:
function myFun(allVals) {
const { val1, val2, val3 } = allVals;
console.log("easy access to individual entries:", val2);
console.log("easy access to all entries:", allVals);
}
回答3:
You cannot use destructuring and simple named positional argument for the same parameter at the same time. What you can do:
Use destructuring for
setupParentClass6
function, but old ES6 approach forsetupChildClass6
(I think this is the best choice, just make name shorter):var setupChildClass6 = (o) => { rangeSlider.setup(o.minVal, o.maxVal); setupParentClass6(o); };
Use old
arguments
object. Butarguments
can slow down a function (V8 particular), so I think it's a bad approach:var setupChildClass6 = ({minVal, maxVal}) => { rangeSlider.setup(minVal, maxVal); setupParentClass6(arguments[0]); };
ES7 has proposal for rest/spread properties (if you don't need
minVal
andmaxVal
insetupParentCalss6
function):var setupChildClass6b = ({minVal, maxVal, ...rest}) => { rangeSlider.setup(minVal, maxVal); setupParentClass6(rest); };
Unfortunately it's not ES6.
来源:https://stackoverflow.com/questions/33185667/naming-destructured-argument-objects