ES6解构函数参数-命名根对象 [英] ES6 destructuring function parameter - naming root object

查看:34
本文介绍了ES6解构函数参数-命名根对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法保留解构函数参数的名称?即根对象的名称?

Is there a way to retain the name of a destructured function argument? I.e., the name of the root object?

在 ES5 中,我可能会这样做(使用继承作为比喻来说明这一点):

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
};

我使用相同的 options 对象来保存多个配置参数.有些参数是父类使用的,有些是子类使用的.

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.

有没有办法在 ES6 中使用解构函数参数来做到这一点?

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?
};

或者我是否需要提取 setupChildClass6() 中的所有选项,以便它们可以单独传递到 setupParentClass6() 中?

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); 
};

这篇关于ES6解构函数参数-命名根对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆