JavaScript Context (this) Saving this for use in nested functions / objects

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

One common pitfall is to try and use this in a nested function or an object, where the context has been lost.

document.getElementById('myAJAXButton').onclick = function(){
    makeAJAXRequest(function(result){
      if (result) { // success
        this.className = 'success';
      }
    })
}

Here the context (this) is lost in the inner callback function. To correct this, you can save the value of this in a variable:

document.getElementById('myAJAXButton').onclick = function(){
    var self = this;
    makeAJAXRequest(function(result){
      if (result) { // success
        self.className = 'success';
      }
    })
}
6

ES6 introduced arrow functions which include lexical this binding. The above example could be written like this:

document.getElementById('myAJAXButton').onclick = function(){
    makeAJAXRequest(result => {
      if (result) { // success
        this.className = 'success';
      }
    })
}


Got any JavaScript Question?