ES6破坏分配

Hen*_*aye 2 javascript ecmascript-6

function drawES2015Chart({size = 'big',cords = {x: 0,y: 0},radius = 25} = {}) {
  console.log(size, cords, radius);
  // do some chart drawing
}

drawES2015Chart({
  cords: {x: 18, y: 30},
  radius: 30
});
Run Code Online (Sandbox Code Playgroud)

我在Mozilla的开发者网站上的Destructuring assignment下找到了这个片段.
我正在学习ES6解构分配但是已经陷入困境,我无法理解这个函数如何接受一个参数并设置默认值?

Mad*_*iha 6

考虑这个更简单的例子:

function foo({ bar }) {
  console.log(bar);
}
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼foo({ bar: 42 });并进入42控制台.

但是,说你需要有一个默认参数,你想barbaz,但要baz选,用的默认值true,你可以做到这一点,像这样:

function foo({ bar, baz = true }) {
  console.log(bar, baz);
}
Run Code Online (Sandbox Code Playgroud)

调用那个foo({ bar: 42 })会导致42, true.

现在说我们希望所有参数都是可选的:

function foo({ bar = 42, baz = true }) {
  console.log(bar, baz);
}

foo({}); // 42, true
// however
foo(); // TypeError: Cannot destructure property `bar` of 'undefined' or 'null'.
Run Code Online (Sandbox Code Playgroud)

哎呀,你不能解构一个没有通过的值.所以你需要那个参数也有一个默认值:

function foo({ bar = 42, baz = true } = {}) {
  console.log(bar, baz);
}

foo(); // 42, true. Yey!
Run Code Online (Sandbox Code Playgroud)

因此,对于您的具体示例:

function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

接受一个可选参数,一个带有三个可选键的对象:

  • size 是一个可选键,默认值为 big
  • cords 是一个可选键,默认值为 {x: 0, y: 0}
  • radius 是一个可选键,默认值为 25

并且由于所有键都是可选的,我们假设空输入等同于空对象,而空对象又将使用键的所有默认值.