JZa*_*ary 1 javascript destructuring ecmascript-6
所以在解构函数默认值的 MDN 文档中,它给出了以下示例。
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)
但是我可以用第一行运行这个例子 function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius =
25})
所以省略了={}部分。我不确定这为什么有效,以及如果较短的形式实际上同样正确,使用较长的形式有什么好处。
按照您的建议重构函数:
function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25}) {
console.log(size, cords, radius);
}
Run Code Online (Sandbox Code Playgroud)
尝试不带参数调用它时会导致错误:
drawES2015Chart(); // throws TypeError
Run Code Online (Sandbox Code Playgroud)
但是,您可以将其称为:
drawES2015Chart({});
Run Code Online (Sandbox Code Playgroud)
所以,最后= {}所做的是让你能够调用
drawES2015Chart();
Run Code Online (Sandbox Code Playgroud)
哪个将默认为
drawES2015Chart({});
Run Code Online (Sandbox Code Playgroud)
哪个将默认为
drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |