我正在从ngOnInit调用一个函数,
public ngOnInit() {
this.idleLogout();
}
public idleLogout() {
let t;
window.onload = resetTimer;
window.addEventListener('scroll', resetTimer, true);
function resetTimer() {
clearTimeout(t);
t = setTimeout(() => {
// this.openLearnMoreModal();
}, 4000);
}
}
public openLearnMoreModal() {
console.log('here')
}我无法从设置的超时函数内部调用openLearnMoreModal函数,这会产生一个错误。
错误TypeError:_this.openLearnMoreModal不是一个函数
发布于 2018-11-01 22:44:48
任一
使用 bind(this):
window.onload = resetTimer.bind(this);
window.addEventListener('scroll', resetTimer.bind(this), true); 或使用arrow function
public idleLogout() {
let t;
const resetTimer = ()=> {
clearTimeout(t);
t = setTimeout(() => {
// this.openLearnMoreModal();
}, 4000);
}
window.onload = resetTimer;
window.addEventListener('scroll', resetTimer, true); 或使用this将其绑定到另一个变量:
public idleLogout() {
let t;
const resetTimer = _resetTimer.bind(this);
window.onload = resetTimer;
window.addEventListener('scroll', resetTimer, true);
function _resetTimer() {
clearTimeout(t);
t = setTimeout(() => {
this.openLearnMoreModal();
}, 4000);
}https://stackoverflow.com/questions/53109861
复制相似问题