Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - How can I access `this` in an event handler?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...