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

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

问题描述

有没有办法保留一个破坏函数参数的名称?也就是根对象的名称?



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

  // ES5:
var setupParentClass5 = function(options){
textEditor.setup(options.rows,options.columns);
};

var setupChildClass5 = function(options){
rangeSlider.setup(options.minVal,options.maxVal);
setupParentClass5(options); //< =我们传递选项对象UP
};

我使用相同的选项对象保存多个配置参数。一些参数由父类使用,一些由子类使用。



有没有办法在ES6中使用解构函数参数?

  // ES6:
var setupParentClass6 =({rows,columns})=> {
textEditor.setup(rows,columns);
};

var setupChildClass6 =({minVal,maxVal})=> {
rangeSlider.setup(minVal,maxVal);
setupParentClass6(/ * ??? * /); //如何传递根选项对象?
};

或者,我需要提取 setupChildClass6(),以便它们可以单独传递到 setupParentClass6()

 code> // ugh。 
var setupChildClass6b =({minVal,maxVal,rows,columns})=> {
rangeSlider.setup(minVal,maxVal);
setupParentClass6({rows,columns});
};


解决方案

我在太多地方有'options'我。我会选择一个额外的代码行。在这个例子中是不值得的,但是在更多的线条上进行解析时,这是一个很好的解决方案。

  var setupChildClass6 =(options)=> {
var {minVal,maxVal} = options;
rangeSlider.setup(minVal,maxVal);
setupParentClass6(options);
};


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

解决方案

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.

var setupChildClass6 = (options) => {
    var {minVal, maxVal} = options;
    rangeSlider.setup(minVal, maxVal);
    setupParentClass6(options); 
};

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

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