[看下面的代码,我不明白为什么filter.formatter
(倒数第二行)可能不确定,因为我之前检查过它是否存在:
type Filter = {
formatter?: {
index: number,
func: (value: string) => void
}
}
const filter: Filter = {
formatter: {
index: 1,
func: (v) => {
return `Label: ${v}`
}
}
}
const data = [['foo', 'bar']]
if (filter.formatter) {
data[filter.formatter.index].forEach(d => {
filter.formatter.func(d) // <-- `formatter` is possibly undefined
})
}
正如注释中的@CRice提及,在for
循环中不会发生。但是我仍然想知道为什么吗?
if (filter.formatter) {
const itemConsumer = (d: string) => { filter.formatter.func(d) };
data[filter.formatter.index].forEach(itemConsumer);
}
// both are the same
const itemConsumer = (d: string) => { filter.formatter.func(d) };
if (filter.formatter) {
data[filter.formatter.index].forEach(itemConsumer);
}
在itemConsumer
中,您仅捕获了对filter
的引用,但未捕获其实际值。因此,在执行filter.formatter
之前,itemConsumer
可能为空。
for
循环不是这种情况,因为您没有为其创建新函数,因此您使用过滤器值,并且编译器可以确保不能定义filter.formatter
。如果您想了解更多有关此的信息,请参阅有关JS的serie of books和专门针对scope and closure的文章