1 回答
TA贡献1777条经验 获得超3个赞
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
添加回答
举报