javascript 是否可以使用 addEventListener 调用类方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21298918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to call a class method with addEventListener?
提问by Azrael
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?
只是我一直想知道的事情。在方法的第二个参数中.addEventListener
,你可以调用“(自定义)类方法”而不是函数吗?
i.e Would something like the following work?
即会像下面这样工作吗?
var object = new ClassName();
document.getElementById('x').addEventListener('click', object.method, false);
回答by meagar
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.
不,你写的东西是行不通的,因为它method
会在没有object
上下文的情况下被调用。内部method
,this
将设置为发起事件的 DOM 元素。
If you want to invoke the method and retain the context, close over the object
variable with a function:
如果要调用该方法并保留上下文,请object
使用函数关闭变量:
var object = new ClassName();
document.getElementById('x').addEventListener('click', function () {
object.method()
}, false);
回答by Sergio A.
Yes. It's possible, just take care with the context. E.g.
是的。这是可能的,只需注意上下文。例如
ClassName.prototype.click_handler = function(el) {
// Here 'this' doesn't refer to the instance
// of ClassName but to the element clicked
}
var object = new ClassName();
document.getElementById('x').addEventListener('click', object.click_handler, false);
回答by Radio
The answers here were helpful but still left me wondering if there was a tidy syntax to do basically the same thing. I didn't want to pass a reference to a class instance to itself, that's just weird.
这里的答案很有帮助,但仍然让我想知道是否有一种整洁的语法来做基本相同的事情。我不想将类实例的引用传递给自身,这很奇怪。
Here's a tidy pattern that keeps everything inside the class with no need to use the instance reference, but a closure instead.
这是一个整洁的模式,它将所有内容都保存在类中,无需使用实例引用,而是使用闭包。
myclass= function(){};
myclass.prototype.addSystemEvents = function(){
var scope = this;
window.addEventListener( 'resize', function(){scope.onWindowResize();}, false);
}
myclass.prototype.onWindowResize = function(){
//do whatever
}
回答by Erick Ribeiro
Yes, it's possible. You need 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 (e) {
object.method(e)
}, false);
If you invoke without inside function, the 'this' would be set to the DOM element which initiated the event.
如果您在没有内部函数的情况下调用,则“this”将设置为启动事件的 DOM 元素。