How use “own” this in event callbacks

In this article i will try to show many possible solution for referencing our object inside event callback function.

I. Create temporary variable. Most frequently is to use created specially variable:


var self=this;
element.addEventListener("event",function(e){
console.log(self);//here self is our this outside
console.log(this);//here this is element on which event handler was called
});

So I created special variable self and self is visible inside callback where this is DOM element reference on which event was called.

II. Use bind to change this inside callback function:


element.addEventListener("event",function(e){
console.log(this);//here is our this outside
console.log(e.currentTarget);//here is element on which event handler was called
}.bind(this));

So I used bind to change this in callback and now this inside callback is the same as this outside. Problem in solution is that we lose this which was DOM element, but event object has property – e.currentTarget which is DOM element which was before this in callback. This solution is cleaner and no need of temporary variable

III. Use new JavaScript features arrow function ( ECMA 6 ):


element.addEventListener("event",(e)=>{
console.log(this);//here is our this outside
console.log(e.currentTarget);//here is element on which event handler was called
});

Third solution is most clear with less code, but not for older browser. This solutions change this inside callback on this outside callback without any code needed.

IV. Use factory function to create callback function


element.addEventListener("event",function(self){
return function(e){
console.log(self);//here is our this outside
console.log(this);//DOM element
};
}(this));

This is most complicated solution, but is better than first one, no need to create tempory variable. We create function which is called with our this as attribute and inside it exists scope where self ===this. Last thing is to return function inside it.