При передаче функции прослушивателю событий вы теряете привязку к this
:
var unlock = function() {
//resume AudioContext (allow playing sound), remove event listeners
context.resume().then(function() {
console.log("context resumed");
// this won't point to the instance when called by listener
this.elem.removeEventListener('touchstart', unlock);
this.elem.removeEventListener('touchend', unlock);
resolve(true);
}, function (reason) {
reject(reason);
});
};
this.elem.addEventListener('touchstart', unlock, false); //error
Функции стрелок или ручной вызов bind(this)
могут это исправить. Функция стрелки будет связывать this
в функции лексически, что означает, что this
будет значением this
от того места, где оно было определено, а не от того, как оно вызывается:
var unlock = () => {
//resume AudioContext (allow playing sound), remove event listeners
context.resume().then(() => {
console.log("context resumed");
this.elem.removeEventListener('touchstart', unlock);
this.elem.removeEventListener('touchend', unlock);
resolve(true);
}, function (reason) {
reject(reason);
});
};
this.elem.addEventListener('touchstart', unlock, false); //error