如何将 JavaScript 类实例传递给 DOM 事件监听器?
我的情况似乎非常棘手。我想将一个对象的实例传递给由同一对象实例创建的 DOM 元素的事件侦听器(如果有意义的话)。
function Object(callback){
this.callback = callback;
this.node = document.createElement('div');
this.send = function(){
document.getElementById('list').appendChild(this.node);
}
this.node.addEventListener('click',function(){/*this.callback() of Object instance needs to go here*/},true);
}
我知道使用 callback()
可以在事件侦听器中工作,但这不是我需要的,因为我将使用实例中的变量,这些变量稍后不会从构造中传递。
我该如何解决这个问题?
I have what seems to be a very tricky situation. I would like to pass an instance of an object to the event listener of a DOM element that was created by that same object instance (if that makes sense).
function Object(callback){
this.callback = callback;
this.node = document.createElement('div');
this.send = function(){
document.getElementById('list').appendChild(this.node);
}
this.node.addEventListener('click',function(){/*this.callback() of Object instance needs to go here*/},true);
}
I know that using callback()
would work inside the event listener, but thats not what I need because I will be using variables from the instance that are not passed from the construct later on.
How can I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
匿名函数改变了this的含义。为了能够在处理程序中使用它,请使用另一个 var,或者不要创建另一个函数:
或
The anonymous function changes the meaning of this. To be able to use it within the handler, use another var, or don't create another function:
or