是否可以使用addEventListener调用类方法? [英] Is it possible to call a class method with addEventListener?
本文介绍了是否可以使用addEventListener调用类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直想知道的事情。在 .addEventListener
方法的第二个参数中,你可以调用(自定义)类方法而不是函数吗?
Just something I've been wondering. In the second parameter in the .addEventListener
method, can you call a "(custom) class method" instead of a function?
即如下所示?
var object = new ClassName();
document.getElementById('x').addEventListener('click', object.method, false);
推荐答案
不,你所写的内容不起作用,在没有 object
作为其上下文的情况下调用方法
。在方法
内,此
将设置为启动该事件的DOM元素。
No, what you've written wouldn't work, in that method
would be invoked without object
as its context. Inside method
, this
would be set to the DOM element which initiated the event.
如果要调用方法并保留上下文,请使用函数关闭对象
变量:
If you want to invoke the method and retain the context, close over the object
variable with a function:
var object = new ClassName();
document.getElementById('x').addEventListener('click', function () {
object.method()
}, false);
这篇关于是否可以使用addEventListener调用类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文