3 回答

TA貢獻1876條經驗 獲得超5個贊
根據您的示例,假設您想要一個匿名函數調用。如果是這樣,是的,您可以使用IIFE執行此操作:
public startDate = this.formatDate(
(() => {
// do some other stuff
return new Date(/* ...args */)
})()
)
但是,為函數命名通常更利于可讀性。

TA貢獻1873條經驗 獲得超9個贊
type GetDate = () => Date
const formatDate = (getDate: GetDate) => {
const date = getDate()
// formate date
}
// usage
const getDateFromInternet = () => API.getDate() // imaginary API which fetches date
const formattedDate = formatDate(getDateFromInternet)

TA貢獻1876條經驗 獲得超6個贊
class A {
public startDate = this.dateFactory();
constructor(
private dateFactory,
) {}
...
}
// somewhere in code
new A(() => new Date());
添加回答
舉報