我正在尝试将类属性作为参数发送给 addEventListener。这样做是因为当事件发生时,我不再处于类(this)的上下文中,并且无法获取\设置属性的值。我需要以某种方式将属性的引用传递给函数。 我知道我可以将属性作为属性添加到事件目标并像这样到达它,但我很确定应该有一个更直接的解决方案。 这是相关代码:
export class ZZZZZ{
constructor()
{
this.activeTooltip = null; //This is the relevant property
}
YYYYFunc()
{
/*thinking of doing it like that*/
var activeTooltip = this.activeTooltip;
cancelDiv.addEventListener('click', function() { XXXFunc(activeTooltip)});
}
XXXFunc(activeTooltip)
{
var A = this.activeTooltip; //I'm not in the context of the class -
//"this" is irrelevant - it is null
var B = activeTooltip;
}
最佳答案
您执行此操作的方式有效并且相当常见,但请注意,您没有理由不能使用 Function#bind
在 XXXFunc
实例中创建 this
:
cancelDiv.addEventListener('click', XXXFunc.bind(this));
bind
返回一个新函数,调用该函数时,将调用原始函数,并将 this
设置为您为 bind
提供的值。因此,这将调用 XXXFunc
,其中 this
引用您的实例,并且 this.activeTooltip
将在其中工作。
还有其他方法。在 ES5 及更早版本中,您可以将 Function#call
与您关闭的变量一起使用:
var _this = this;
cancelDiv.addEventListener('click', function() { XXXFunc.call(_this)});
在 ES2015+ 中,您可以使用箭头函数代替变量,因为箭头函数在 this
本身上结束:
cancelDiv.addEventListener('click', () => XXXFunc.call(this));
在这两种情况下,XXXFunc
中的 this
都会引用您的实例,因此 this.activeTooltip
可以工作。
当然,如果XXXFunc
在实例上有一个方法,它会更干净:
ES5-使用Function#bind
:
cancelDiv.addEventListener('click', this.XXXFunc.bind(this));
ES2015+ 使用箭头函数:
cancelDiv.addEventListener('click', () => this.XXXFunc());
关于javascript - 将类属性的引用传递给 addEventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927114/