javascript - 将函数执行定义为参数
问题描述
我使用 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 :(
解决方案
根据文档 - 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 })
推荐阅读
- xcode - How can I get the Xcode debugger to step into the assembly of a function?
- hyperledger-fabric - Multi-signature Transaction in Hyper-ledger Fabric
- sql - 计算 postgresql 中数字列的汇总统计信息
- c# - 带有用于发现端点的授权标头的 JwtBearerHandler
- excel - VBA如何从一个文件夹中打开/保存/关闭带有扩展名的文件
- angular - 多种反应形式输入值
- reactjs - 来自 api 的订单数据
- javascript - Mapbox 中 Geojson 瓦片集的自定义符号系统
- python - 将终端文件参数传递给python脚本
- scala - Spark SQL 将正常的内部连接检测为交叉连接