【发布时间】:2017-12-02 14:00:27
【问题描述】:
Illegal invocation TypeError: Illegal invocation 在使用变量回调调用 setTimeout 时抛出。我读到当this 引用回调中的另一个对象并且使用bind 或箭头函数来解决这个问题时,就会发生这种情况。但是,我的回调中没有 this。
代码如下:
class AlarmService {
constructor(callback) {
this._alarms = {};
this.setTimeout = window.setTimeout;
this.clearTimeout = window.clearTimeout;
this._callback = callback || function () {};
}
create(alarmName, when, title, message) {
this._alarms[alarmName] = {
'title': title,
'message': message
};
this._alarms.timeout = this.setTimeout(this._callback, when - Date.now(),
this._alarms[alarmName]);
}
}
let alarms = new AlarmService(function (alarm) {
console.log('Alarm', alarm.name);
});
// Exception is thrown here
alarms.create('alarmName', Date.now() + 3000, 'Title', 'Message');
注意我使用的是 babel 和 es2015。
【问题讨论】:
-
该函数抛出错误,因为您已将对它的引用复制到您自己的对象,然后您使用自己的对象作为
this上下文调用它。回调不引用this没有区别。问题是您调用的是this.setTimeout()而不是window.setTimeout()。