首页 > 解决方案 > 将函数执行定义为参数

问题描述

我使用 ES6 中的解构函数,我将函数执行定义为参数

这是一个例子

  reformatDate(date: Date) {
    const dd = date.getDate();
    const mm = date.getMonth() + 1;
    const yyyy = date.getFullYear();
    return `${yyyy}-${mm < 10 ? '0' + mm : mm}-${dd < 10 ? '0' + dd : dd}`;
  }

  reformatDate(new Date('2013-3-3'))

通过解构,我们可以使用

  const reformatDate = ({getDate: dd = dd(), getMonth: mm = mm(), getFullYear:yyyy=yyyy() })  => 
   `${yyyy}-${mm < 10 ? '0' + mm : mm}-${dd < 10 ? '0' + dd : dd}`;

  reformatDate(new Date('2013-3-3'))

  const reformatDate = ({getDate: dd = dd(), getMonth: mm = mm(), getFullYear:yyyy=yyyy() })  => `${yyyy}-${mm < 10 ? '0' + mm : mm}-${dd < 10 ? '0' + dd : dd}`;

  console.log(reformatDate(new Date('2013-3-3')))

但有一些错误

function getFullYear() { [native code] }-function getMonth() { [native code] }-function getDate() { [native code] }

我用了

const reformatDate = ({getDate: dd = dd.call ,....

but same error :( 

标签: javascriptecmascript-6destructuring

解决方案


根据文档 - MDN

如果未传递任何值或未定义,则默认函数参数允许使用默认值初始化命名参数。

例如,如果您的代码如下:

function test(x = 10) {
  console.log(x);
}
test();
test(5)

x如果未通过,将应用默认值。

在您的情况下,由于您在参数上使用破坏模式,因此如果破坏后的值是,则将应用默认值undefined

以下是一个示例:

function test({x = 10, y = 20}) {
  console.log(x, y);
}
test({ y: 5 });
test({ x: 4, y: 11 })


推荐阅读