传递诸如getTime()之类的日期方法作为回调

时间:2020-09-16 14:45:06

标签: javascript function date methods callback

我想将诸如getMinutes()getTime()getDay()之类的日期对象方法作为回调传递给诸如以下的函数:

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

或更高级:

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

我有什么选择?

3 个答案:

答案 0 :(得分:3)

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

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 :(得分:1)

尝试:

date[callback]()

var date=new Date();

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

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

答案 2 :(得分: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"