如何在事件处理程序中访问`this`? [英] How can I access `this` in an event handler?

查看:90
本文介绍了如何在事件处理程序中访问`this`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



简化代码:

  function myClass()
{
this.domElement = document.createElement(canvas);
this.domElement.addEventListener(click,this.handleClick);
}
myClass.prototype.handleClick = function(evt)
{
alert(Clicked!);
//如何修改`this`对象?
}

现在我要修改一些属性和变量的myClass实例在code> handleClick()。但是这个当然是指画布对象。



问题:我访问事件处理程序中对象的这个

解决方案

可以通过关闭对您的实例的引用来完成,并使用apply强制函数的范围:



在第1步中,我的示例显示了如何这个是被点击的元素: http://jsfiddle.net/JAAulde / GJXpQ /



在第2步中,我有一个例子,它在你的构造函数中存储对你的实例的引用,然后设置一个匿名函数作为点击处理程序,将您的点击方法称为存储引用。 http://jsfiddle.net/JAAulde/GJXpQ/1/ 这导致您的点击处理程序中的这个作为您的实例,如果您不需要访问被点击的元素,将适用于您。



在第3步中,我存储了相同的引用,并使用了一个匿名函数,但是在该函数内部,我抓住了在anon函数中点击的参数,我将实例的引用添加到这些参数中,我称之为点击处理程序在点击的元素的范围内,并传递新的参数集。 http://jsfiddle.net/JAAulde/GJXpQ/2/ 使用这种方法,在点击处理程序我可以通过这个 myClass 通过实例访问点击的元素



我希望这有帮助。这可能很混乱,所以如果需要,可以提问。


I have a class which creates a DOM element and has to capture all click events.

Simplified code:

function myClass()
{
  this.domElement = document.createElement("canvas");
  this.domElement.addEventListener("click", this.handleClick);
}
myClass.prototype.handleClick = function(evt)
{
  alert("Clicked!");
  // How to modify `this` object?
}

Now I want to modify some attributes and variables of the myClass instance in handleClick(). But this refers to the canvas object, of course.

Question: How can I access this of an object in an event handler?

解决方案

This can be accomplished via closing over a reference to your instance and using apply to force the scope of a function:

In step 1 I have your example showing how this is the element which was clicked: http://jsfiddle.net/JAAulde/GJXpQ/

In step 2 I have an example which stores a reference to your instance in your constructor, then sets an anonymous function as the click handler and calls your click method off the stored reference. http://jsfiddle.net/JAAulde/GJXpQ/1/ This causes this within your click handler to be your instance and will work for you if you do not need access to the element which was clicked.

In step 3 I have stored the same reference, and used an anonymous function, but inside that function I grab the arguments which come into the anon function on click, I add the reference to the instance to those arguments, and I call the click handler in scope of the clicked element and pass the new set of arguments. http://jsfiddle.net/JAAulde/GJXpQ/2/ Using this methodology, inside the click handler I can access the clicked element via this, and the instance of myClass via instance.

I hope this helps. It can be quite confusing, so ask questions if needed.

这篇关于如何在事件处理程序中访问`this`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆