Saving this for use in nested functions objects

suggest change

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';
      }
    })
}

The inner function is called as a plain callback, so its this is not the button. In strict mode that this is undefined and this.className throws. In non-strict code it is the global object. Save the outer this in a variable:

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

An arrow function uses the this of the surrounding function. The handler must stay a normal function so that this is the button:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents