2017-02-23 229 views
6

这里有一个空的对象分配的大括号对象是代码,JS函数声明:在参数声明

export function createConnect({ 
    connectHOC = connectAdvanced, 
    mapStateToPropsFactories = defaultMapStateToPropsFactories, 
    mapDispatchToPropsFactories = defaultMapDispatchToPropsFactories, 
    mergePropsFactories = defaultMergePropsFactories, 
    selectorFactory = defaultSelectorFactory 
} = {}) {...} 

是什么{connectHOC = connectAdvanced ...} = {}指的是函数参数声明中?

我知道

= {} 

可能意味着功能参数的默认值,但什么是对以前的括号中的代码使用?

+2

我不能完全肯定的是,但是所述第一部分('{connectHOC = ......... = defaultSelectorFactory}')不是一个对象,它是与几个变量声明一个块。一个对象会使用冒号,而不是等号。 –

+1

这是参数的默认值和解构的组合。让我们感到惊讶的是,我们似乎并没有在SO上同时覆盖这两个问题,无论是这次还是我的谷歌都在让我失望。 –

+1

[This is close](http:// stackoverflow。com/questions/26578167/es6-object-destructuring-default-parameters),但不是很愚蠢。 [也是这个](http://stackoverflow.com/questions/34275971/how-to-destructure-option-argument-with-all-default-values-in-es6)。他们都解释了这里发生了什么,但从OP的角度来看,他们知道他们希望将缺省值分配给解构参数,而不是“这是什么语法”方法。 –

回答

5

这是ES2015语法。您的函数声明将Destructuring assignment与默认值组合在一起。

这是使用对象的基本解构赋值:

var {a, b} = {a: "foo", b: "bar"}; 
 
console.log(a); // "foo" 
 
console.log(b); // "bar"

您可以添加默认值左侧:

var {a = "foo", b = "bar"} = {}; 
 
console.log(a); // "foo" 
 
console.log(b); // "bar"

当你声明一个函数时指定的参数,你不使用var,并与解构的对象将是相同的:

function test({a = "foo", b = "bar"}){ 
 
    console.log(a + b); 
 
} 
 
test({}); // "foobar" 
 
test({b: "boo"}); // "fooboo"

,当然,你可以定义默认值,这样你的函数就不必接受任何参数。

function test({a = "foo", b = "bar"} = {}){ 
 
    console.log(a + b); 
 
} 
 
test(); // "foobar"

+0

不错的其他例子。 – msanford

3

这只是使用解构来完成默认参数的方式。您需要按照您的建议默认最后一位。

考虑以下,其中,相同的例子使用一个destructuring assignment

function withDefault({parameter=something} = {}) { 
 
console.log(parameter) 
 
} 
 

 
let something = 1; 
 
withDefault();

与这一个,其中缺少缺省,并且引发一个错误:

function withoutDefault({parameter=something}) { 
 
console.log(parameter) 
 
} 
 

 
let something = 1; 
 
withoutDefault(); 
 
// It needs to be called as withoutDefault({}), withoutDefault(1) or 
 
// with some value, since the function signature doesn't define a default 
 
// in this case.