1 回答

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個贊
一種常見的處理方法是返回一個函數(shù):
private attach() {
const listener = this.getListener()
this.targets.forEach(target => {
target.addEventListener('click', listener, false)
})
}
private getListener() {
const self = this
return function (e: Event) {
// self if EventListenerHelper this
// this is Event this
}
}
但我看不出它有多大好處,因?yàn)閠his在你傳遞給的函數(shù)內(nèi)部addEventListener等于event.currentTarget,所以你可以只綁定你的監(jiān)聽器并使用屬性而不是this:
constructor() {
// ...
this.listener = this.listener.bind(this)
}
private listener(e) {
// this is EventListenerHelper this
// e.currentTarget is Event this
}
添加回答
舉報