如何正确使用 lambda 函数作为参数?

如果我有这样的陈述:

public startDate = this.formatDate(new Date());

我不想传递 new Date(),而是传递函数创建的日期。我知道我能做到:

public startDate = this.formatDate(this.getDateFunc());

但是有没有办法用 lambda 函数来做到这一点?我尝试查找它,但我发现的所有帖子都在谈论函数作为定义中的参数。

我想做类似的事情:

public startDate = this.formatDate(() => {...});


斯蒂芬大帝
浏览 118回答 3
3回答

慕运维8079593

根据您的示例,假设您想要一个匿名函数调用。如果是这样,是的,您可以使用IIFE执行此操作:public startDate = this.formatDate(    (() => {        // do some other stuff        return new Date(/* ...args */)    })())但是,为函数命名通常更利于可读性。

眼眸繁星

type GetDate = () => Dateconst formatDate = (getDate: GetDate) => { const date = getDate() // formate date }// usageconst getDateFromInternet = () => API.getDate() // imaginary API which fetches dateconst formattedDate = formatDate(getDateFromInternet)

HUX布斯

class A {  public startDate = this.dateFactory();  constructor(    private dateFactory,  ) {}  ...}// somewhere in codenew A(() => new Date());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript