将像 getTime() 这样的日期方法作为回调传递

3

我想将Date对象的方法,例如getMinutes()getTime()getDay()作为回调函数传递给以下函数:

formatDate = (date, callback) => {
    date.callback()
}

更高级的技术:
formatDateArray = (dateArray, callback) => {
        dateArray.map(date => date.callback())
    }

我的可选方案有哪些?


1
你可以使用方括号表示法来动态访问callback的值: date[callback]()。用法类似于formatDate(date, "getMinutes") - Nick Parsons
3个回答

3
您可以使用Function.prototype.call,将日期对象作为this参数传递来调用Date方法:

const getTime = Date.prototype.getTime;
const getDay = Date.prototype.getDay;
const getMinutes = Date.prototype.getMinutes

formatDateArray = (dateArray, callback) => {
  return dateArray.map(date => callback.call(date))
}

console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getTime));
console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getDay));
console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getMinutes));


1
我会使用柯里化函数来完成这个任务:第一次调用接受你的回调函数(以及其他可选参数;稍后详细介绍),第二次调用接受你的日期。
const formatDate = (fn, ...args) => date => fn.apply(date, args);

我们可以使用它与 Date#getDate 一起:
const getDate = formatDate(Date.prototype.getDate);

因为getDate现在是一个“等待”它的最后一个参数(即日期)的函数,所以您也可以将其与Array#map一起使用:
// moon landing dates
const apollo11 = new Date('1969-07-20');
const apollo12 = new Date('1969-11-21');

getDate(apollo11);
//=> 20

[apollo11, apollo12].map(getDate);
//=> [20, 21];

一些日期方法需要传入参数,例如Date#toLocaleDateString。如果不能使用它们将是一件遗憾的事情。由于它们是在实际日期之前提供的,因此我们可以创建专门的函数:
const toUsDate = formatDate(Date.prototype.toLocaleDateString, 'en-US');
const toGbDate = formatDate(Date.prototype.toLocaleDateString, 'en-GB');

toUsDate(apollo11); //=> "7/20/1969"
toGbDate(apollo11); //=> "20/07/1969"

1

尝试:

date[callback]()

var date=new Date();

var callbacks=["toLocaleString", "getFullYear", "valueOf"];

callbacks.forEach(cb=>console.log(cb+": "+date[cb]()));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接