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

坚强是说给别人听的谎言 提交于 2019-11-29 14:31:56

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.

You can do it like this:

function myClass() {
  var self = this;

  this.domElement = document.createElement("canvas");
  this.domElement.addEventListener("click", function(evt){
      // use self here
  });
}

Since listener is actually a closure, it maintains reference to the variable self, which is object you're observing. Actual this, as you figured it out, references canvas element.

Another way that'd work, and keep methods seperated:

function myClass(){
  var self = this;

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

Now this one uses Function.call and assigns what this references to.

You could use .bind, which "freezes" the this value with a preset one: http://jsfiddle.net/TKAHg/.

.bind returns a new function which does the same thing as the original function, but it sets the this so that you can rely on it being the value you provided.

Although .bind is not available on older browsers, MDC has a shim for it.

// bind 'this' value inside handleClick when clicked
this.domElement.addEventListener("click", this.handleClick.bind(this));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!