[英]define function execute as arguments
我使用 ES6 中的析构函数,我将函数 execute 定义为参数
这是一个例子
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() { [本机代码] }-function getMonth() { [本机代码] }-function getDate() { [本机代码] }
我用了
const reformatDate = ({getDate: dd = dd.call ,....
but same error :(
= dd()
等语法不调用该方法,它只是设置一个默认参数。 您需要自己在函数内部调用这些方法。 但是,您不能单独调用解构函数,因为this
将不再绑定到 Date 对象。 要执行您想要的操作,您需要保留原始日期。 您可以执行此操作的一种方法是将日期两次传递给您的函数,或者使用对象并解构日期属性。 然后,您需要在您的方法上使用.call()
将this
重新分配回您的日期对象,如下所示:
const reformatDate = ({d, d: {getDate: dd, getMonth: mm , getFullYear:yyyy}}) => `${yyyy.call(d)}-${mm.call(d) < 10 ? '0' + mm.call(d) : mm.call(d)}-${dd.call(d) < 10 ? '0' + dd.call(d) : dd.call(d)}`; console.log(reformatDate({d: new Date('2013-3-3')}))
但是,这首先违背了解构的目的,因为您可以直接在日期对象上使用这些方法。 此外,我发现它比没有解构的第一个示例更难阅读和解释,因此,我非常喜欢你的第一个代码块而不是这种方法。
根据文档 - 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 })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.